home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60src.lha / Vim / vim60 / src / fold.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-09-26  |  76.8 KB  |  3,132 lines

  1. /* vim:set ts=8 sts=4 sw=4:
  2.  * vim600:fdm=marker fdl=1 fdc=3:
  3.  *
  4.  * VIM - Vi IMproved    by Bram Moolenaar
  5.  *
  6.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  7.  * Do ":help credits" in Vim to see a list of people who contributed.
  8.  * See README.txt for an overview of the Vim source code.
  9.  */
  10.  
  11. /*
  12.  * fold.c: code for folding
  13.  */
  14.  
  15. #include "vim.h"
  16.  
  17. #if defined(FEAT_FOLDING) || defined(PROTO)
  18.  
  19. /* local declarations. {{{1 */
  20. /* typedef fold_T {{{2 */
  21. /*
  22.  * The toplevel folds for each window are stored in the w_folds growarray.
  23.  * Each toplevel fold can contain an array of second level folds in the
  24.  * fd_nested growarray.
  25.  * The info stored in both growarrays is the same: An array of fold_T.
  26.  */
  27. typedef struct
  28. {
  29.     linenr_T    fd_top;        /* first line of fold; for nested fold
  30.                  * relative to parent */
  31.     linenr_T    fd_len;        /* number of lines in the fold */
  32.     garray_T    fd_nested;    /* array of nested folds */
  33.     char    fd_flags;    /* see below */
  34.     char    fd_small;    /* TRUE, FALSE or MAYBE: fold smaller than
  35.                    'foldminlines'; MAYBE applies to nested
  36.                    folds too */
  37. } fold_T;
  38.  
  39. #define FD_OPEN        0    /* fold is open (nested ones can be closed) */
  40. #define FD_CLOSED    1    /* fold is closed */
  41. #define FD_LEVEL    2    /* depends on 'foldlevel' (nested folds too) */
  42.  
  43. #define MAX_LEVEL    20    /* maximum fold depth */
  44.  
  45. /* static functions {{{2 */
  46. static int checkCloseRec __ARGS((garray_T *gap, linenr_T lnum, int level));
  47. static int foldFind __ARGS((garray_T *gap, linenr_T lnum, fold_T **fpp));
  48. static int foldLevelWin __ARGS((win_T *wp, linenr_T lnum));
  49. static void checkupdate __ARGS((win_T *wp));
  50. static void setFoldRepeat __ARGS((linenr_T lnum, long count, int open));
  51. static linenr_T setManualFold __ARGS((linenr_T lnum, int opening, int recurse, int *donep));
  52. static void foldOpenNested __ARGS((fold_T *fpr));
  53. static void deleteFoldEntry __ARGS((garray_T *gap, int idx, int recursive));
  54. static void foldMarkAdjustRecurse __ARGS((garray_T *gap, linenr_T line1, linenr_T line2, long amount, long amount_after));
  55. static int getDeepestNestingRecurse __ARGS((garray_T *gap));
  56. static int check_closed __ARGS((win_T *win, fold_T *fp, int *use_levelp, int level, int *maybe_smallp, linenr_T lnum_off));
  57. static void checkSmall __ARGS((win_T *wp, fold_T *fp, linenr_T lnum_off));
  58. static void setSmallMaybe __ARGS((garray_T *gap));
  59. static void foldCreateMarkers __ARGS((linenr_T start, linenr_T end));
  60. static void foldAddMarker __ARGS((linenr_T lnum, char_u *marker, int markerlen));
  61. static void deleteFoldMarkers __ARGS((fold_T *fp, int recursive, linenr_T lnum_off));
  62. static void foldDelMarker __ARGS((linenr_T lnum, char_u *marker, int markerlen));
  63. static void foldUpdateIEMS __ARGS((win_T *wp, linenr_T top, linenr_T bot));
  64. static void parseMarker __ARGS((win_T *wp));
  65.  
  66. static char *e_nofold = N_("No fold found");
  67.  
  68. /*
  69.  * While updating the folds lines between invalid_top and invalid_bot have an
  70.  * undefined fold level.  Only used for the window currently being updated.
  71.  */
  72. static linenr_T invalid_top = (linenr_T)0;
  73. static linenr_T invalid_bot = (linenr_T)0;
  74.  
  75. /* Flags used for "done" argument of setManualFold. */
  76. #define DONE_NOTHING    0
  77. #define DONE_ACTION    1    /* did close or open a fold */
  78. #define DONE_FOLD    2    /* did find a fold */
  79.  
  80. static int foldstartmarkerlen;
  81. static char_u *foldendmarker;
  82. static int foldendmarkerlen;
  83.  
  84. /* Exported folding functions. {{{1 */
  85. /* copyFoldingState() {{{2 */
  86. #if defined(FEAT_WINDOWS) || defined(PROTO)
  87. /*
  88.  * Copy that folding state from window "wp_from" to window "wp_to".
  89.  */
  90.     void
  91. copyFoldingState(wp_from, wp_to)
  92.     win_T    *wp_from;
  93.     win_T    *wp_to;
  94. {
  95.     wp_to->w_fold_manual = wp_from->w_fold_manual;
  96.     wp_to->w_foldinvalid = wp_from->w_foldinvalid;
  97.     cloneFoldGrowArray(&wp_from->w_folds, &wp_to->w_folds);
  98. }
  99. #endif
  100.  
  101. /* hasAnyFolding() {{{2 */
  102. /*
  103.  * Return TRUE if there may be folded lines in the current window.
  104.  */
  105.     int
  106. hasAnyFolding(win)
  107.     win_T    *win;
  108. {
  109.     /* very simple now, but can become more complex later */
  110.     return (win->w_p_fen
  111.         && (!foldmethodIsManual(win) || win->w_folds.ga_len > 0));
  112. }
  113.  
  114. /* hasFolding() {{{2 */
  115. /*
  116.  * Return TRUE if line "lnum" in the current window is part of a closed
  117.  * fold.
  118.  * When returning TRUE, *firstp and *lastp are set to the first and last
  119.  * lnum of the sequence of folded lines (skipped when NULL).
  120.  */
  121.     int
  122. hasFolding(lnum, firstp, lastp)
  123.     linenr_T    lnum;
  124.     linenr_T    *firstp;
  125.     linenr_T    *lastp;
  126. {
  127.     return hasFoldingWin(curwin, lnum, firstp, lastp, TRUE, NULL);
  128. }
  129.  
  130. /* hasFoldingWin() {{{2 */
  131.     int
  132. hasFoldingWin(win, lnum, firstp, lastp, cache, infop)
  133.     win_T    *win;
  134.     linenr_T    lnum;
  135.     linenr_T    *firstp;
  136.     linenr_T    *lastp;
  137.     int        cache;        /* when TRUE: use cached values of window */
  138.     foldinfo_T    *infop;        /* where to store fold info */
  139. {
  140.     int        had_folded = FALSE;
  141.     linenr_T    first = 0;
  142.     linenr_T    last = 0;
  143.     linenr_T    lnum_rel = lnum;
  144.     int        x;
  145.     fold_T    *fp;
  146.     int        level = 0;
  147.     int        use_level = FALSE;
  148.     int        maybe_small = FALSE;
  149.     garray_T    *gap;
  150.     int        low_level = 0;;
  151.  
  152.     checkupdate(win);
  153.     /*
  154.      * Return quickly when there is no folding at all in this window.
  155.      */
  156.     if (!hasAnyFolding(win))
  157.     {
  158.     if (infop != NULL)
  159.         infop->fi_level = 0;
  160.     return FALSE;
  161.     }
  162.  
  163.     if (cache)
  164.     {
  165.     /*
  166.      * First look in cached info for displayed lines.  This is probably
  167.      * the fastest, but it can only be used if the entry is still valid.
  168.      */
  169.     x = find_wl_entry(win, lnum);
  170.     if (x >= 0)
  171.     {
  172.         first = win->w_lines[x].wl_lnum;
  173.         last = win->w_lines[x].wl_lastlnum;
  174.         had_folded = win->w_lines[x].wl_folded;
  175.     }
  176.     }
  177.  
  178.     if (first == 0)
  179.     {
  180.     /*
  181.      * Recursively search for a fold that contains "lnum".
  182.      */
  183.     gap = &win->w_folds;
  184.     for (;;)
  185.     {
  186.         if (!foldFind(gap, lnum_rel, &fp))
  187.         break;
  188.  
  189.         /* Remember lowest level of fold that starts in "lnum". */
  190.         if (lnum_rel == fp->fd_top && low_level == 0)
  191.         low_level = level + 1;
  192.  
  193.         first += fp->fd_top;
  194.         last += fp->fd_top;
  195.  
  196.         /* is this fold closed? */
  197.         had_folded = check_closed(win, fp, &use_level, level,
  198.                            &maybe_small, lnum - lnum_rel);
  199.         if (had_folded)
  200.         {
  201.         /* Fold closed: Set last and quit loop. */
  202.         last += fp->fd_len - 1;
  203.         break;
  204.         }
  205.  
  206.         /* Fold found, but it's open: Check nested folds.  Line number is
  207.          * relative to containing fold. */
  208.         gap = &fp->fd_nested;
  209.         lnum_rel -= fp->fd_top;
  210.         ++level;
  211.     }
  212.     }
  213.  
  214.     if (!had_folded)
  215.     {
  216.     if (infop != NULL)
  217.     {
  218.         infop->fi_level = level;
  219.         infop->fi_lnum = lnum - lnum_rel;
  220.         infop->fi_low_level = low_level == 0 ? level : low_level;
  221.     }
  222.     return FALSE;
  223.     }
  224.  
  225.     if (lastp != NULL)
  226.     *lastp = last;
  227.     if (firstp != NULL)
  228.     *firstp = first;
  229.     if (infop != NULL)
  230.     {
  231.     infop->fi_level = level + 1;
  232.     infop->fi_lnum = first;
  233.     infop->fi_low_level = low_level == 0 ? level + 1 : low_level;
  234.     }
  235.     return TRUE;
  236. }
  237.  
  238. /* foldLevel() {{{2 */
  239. /*
  240.  * Return fold level at line number "lnum" in the current window.
  241.  */
  242.     int
  243. foldLevel(lnum)
  244.     linenr_T    lnum;
  245. {
  246.     /* While updating the folds lines between invalid_top and invalid_bot have
  247.      * an undefined fold level.  Otherwise update the folds first. */
  248.     if (invalid_top == (linenr_T)0)
  249.     checkupdate(curwin);
  250.     else if (lnum >= invalid_top && lnum <= invalid_bot)
  251.     return -1;
  252.  
  253.     /* Return quickly when there is no folding at all in this window. */
  254.     if (!hasAnyFolding(curwin))
  255.     return 0;
  256.  
  257.     return foldLevelWin(curwin, lnum);
  258. }
  259.  
  260. /* lineFolded()    {{{2 */
  261. /*
  262.  * Low level function to check if a line is folded.  Doesn't use any caching.
  263.  * Return TRUE if line is folded.
  264.  * Return FALSE if line is not folded.
  265.  * Return MAYBE if the line is folded when next to a folded line.
  266.  */
  267.     int
  268. lineFolded(win, lnum)
  269.     win_T    *win;
  270.     linenr_T    lnum;
  271. {
  272.     return foldedCount(win, lnum, NULL) != 0;
  273. }
  274.  
  275. /* foldedCount() {{{2 */
  276. /*
  277.  * Count the number of lines that are folded at line number "lnum".
  278.  * Normally "lnum" is the first line of a possible fold, and the returned
  279.  * number is the number of lines in the fold.
  280.  * Doesn't use caching from the displayed window.
  281.  * Returns number of folded lines from "lnum", or 0 if line is not folded.
  282.  * When "infop" is not NULL, fills *infop with the fold level info.
  283.  */
  284.     long
  285. foldedCount(win, lnum, infop)
  286.     win_T    *win;
  287.     linenr_T    lnum;
  288.     foldinfo_T    *infop;
  289. {
  290.     linenr_T    last;
  291.  
  292.     if (hasFoldingWin(win, lnum, NULL, &last, FALSE, infop))
  293.     return (long)(last - lnum + 1);
  294.     return 0;
  295. }
  296.  
  297. /* foldmethodIsManual() {{{2 */
  298. /*
  299.  * Return TRUE if 'foldmethod' is "manual"
  300.  */
  301.     int
  302. foldmethodIsManual(wp)
  303.     win_T    *wp;
  304. {
  305.     return (wp->w_p_fdm[3] == 'u');
  306. }
  307.  
  308. /* foldmethodIsIndent() {{{2 */
  309. /*
  310.  * Return TRUE if 'foldmethod' is "indent"
  311.  */
  312.     int
  313. foldmethodIsIndent(wp)
  314.     win_T    *wp;
  315. {
  316.     return (wp->w_p_fdm[0] == 'i');
  317. }
  318.  
  319. /* foldmethodIsExpr() {{{2 */
  320. /*
  321.  * Return TRUE if 'foldmethod' is "expr"
  322.  */
  323.     int
  324. foldmethodIsExpr(wp)
  325.     win_T    *wp;
  326. {
  327.     return (wp->w_p_fdm[1] == 'x');
  328. }
  329.  
  330. /* foldmethodIsMarker() {{{2 */
  331. /*
  332.  * Return TRUE if 'foldmethod' is "marker"
  333.  */
  334.     int
  335. foldmethodIsMarker(wp)
  336.     win_T    *wp;
  337. {
  338.     return (wp->w_p_fdm[2] == 'r');
  339. }
  340.  
  341. /* foldmethodIsSyntax() {{{2 */
  342. /*
  343.  * Return TRUE if 'foldmethod' is "syntax"
  344.  */
  345.     int
  346. foldmethodIsSyntax(wp)
  347.     win_T    *wp;
  348. {
  349.     return (wp->w_p_fdm[0] == 's');
  350. }
  351.  
  352. /* foldmethodIsDiff() {{{2 */
  353. /*
  354.  * Return TRUE if 'foldmethod' is "diff"
  355.  */
  356.     int
  357. foldmethodIsDiff(wp)
  358.     win_T    *wp;
  359. {
  360.     return (wp->w_p_fdm[0] == 'd');
  361. }
  362.  
  363. /* closeFold() {{{2 */
  364. /*
  365.  * Close fold for current window at line "lnum".
  366.  * Repeat "count" times.
  367.  */
  368.     void
  369. closeFold(lnum, count)
  370.     linenr_T    lnum;
  371.     long    count;
  372. {
  373.     setFoldRepeat(lnum, count, FALSE);
  374. }
  375.  
  376. /* closeFoldRecurse() {{{2 */
  377. /*
  378.  * Close fold for current window at line "lnum" recursively.
  379.  */
  380.     void
  381. closeFoldRecurse(lnum)
  382.     linenr_T    lnum;
  383. {
  384.     (void)setManualFold(lnum, FALSE, TRUE, NULL);
  385. }
  386.  
  387. /* opFoldRange() {{{2 */
  388. /*
  389.  * Open or Close folds for current window in lines "first" to "last".
  390.  * Used for "zo", "zO", "zc" and "zC" in Visual mode.
  391.  */
  392.     void
  393. opFoldRange(first, last, opening, recurse, had_visual)
  394.     linenr_T    first;
  395.     linenr_T    last;
  396.     int        opening;    /* TRUE to open, FALSE to close */
  397.     int        recurse;    /* TRUE to do it recursively */
  398.     int        had_visual;    /* TRUE when Visual selection used */
  399. {
  400.     int        done = DONE_NOTHING;    /* avoid error messages */
  401.     linenr_T    lnum;
  402.     linenr_T    lnum_next;
  403.  
  404.     for (lnum = first; lnum <= last; lnum = lnum_next + 1)
  405.     {
  406.     lnum_next = lnum;
  407.     /* Opening one level only: next fold to open is after the one going to
  408.      * be opened. */
  409.     if (opening && !recurse)
  410.         (void)hasFolding(lnum, NULL, &lnum_next);
  411.     (void)setManualFold(lnum, opening, recurse, &done);
  412.     /* Closing one level only: next line to close a fold is after just
  413.      * closed fold. */
  414.     if (!opening && !recurse)
  415.         (void)hasFolding(lnum, NULL, &lnum_next);
  416.     }
  417.     if (done == DONE_NOTHING)
  418.     EMSG(_(e_nofold));
  419. #ifdef FEAT_VISUAL
  420.     /* Force a redraw to remove the Visual highlighting. */
  421.     if (had_visual)
  422.     redraw_curbuf_later(INVERTED);
  423. #endif
  424. }
  425.  
  426. /* openFold() {{{2 */
  427. /*
  428.  * Open fold for current window at line "lnum".
  429.  * Repeat "count" times.
  430.  */
  431.     void
  432. openFold(lnum, count)
  433.     linenr_T    lnum;
  434.     long    count;
  435. {
  436.     setFoldRepeat(lnum, count, TRUE);
  437. }
  438.  
  439. /* openFoldRecurse() {{{2 */
  440. /*
  441.  * Open fold for current window at line "lnum" recursively.
  442.  */
  443.     void
  444. openFoldRecurse(lnum)
  445.     linenr_T    lnum;
  446. {
  447.     (void)setManualFold(lnum, TRUE, TRUE, NULL);
  448. }
  449.  
  450. /* foldOpenCursor() {{{2 */
  451. /*
  452.  * Open folds until the cursor line is not in a closed fold.
  453.  */
  454.     void
  455. foldOpenCursor()
  456. {
  457.     int        done;
  458.  
  459.     checkupdate(curwin);
  460.     if (hasAnyFolding(curwin))
  461.     for (;;)
  462.     {
  463.         done = DONE_NOTHING;
  464.         (void)setManualFold(curwin->w_cursor.lnum, TRUE, FALSE, &done);
  465.         if (!(done & DONE_ACTION))
  466.         break;
  467.     }
  468. }
  469.  
  470. /* newFoldLevel() {{{2 */
  471. /*
  472.  * Set new foldlevel for current window.
  473.  */
  474.     void
  475. newFoldLevel()
  476. {
  477.     fold_T    *fp;
  478.     int        i;
  479.  
  480.     checkupdate(curwin);
  481.     if (curwin->w_fold_manual)
  482.     {
  483.     /* Set all flags for the first level of folds to FD_LEVEL.  Following
  484.      * manual open/close will then change the flags to FD_OPEN or
  485.      * FD_CLOSED for those folds that don't use 'foldlevel'. */
  486.     fp = (fold_T *)curwin->w_folds.ga_data;
  487.     for (i = 0; i < curwin->w_folds.ga_len; ++i)
  488.         fp[i].fd_flags = FD_LEVEL;
  489.     curwin->w_fold_manual = FALSE;
  490.     }
  491.     changed_window_setting();
  492. }
  493.  
  494. /* foldCheckClose() {{{2 */
  495. /*
  496.  * Apply 'foldlevel' to all folds that don't contain the cursor.
  497.  */
  498.     void
  499. foldCheckClose()
  500. {
  501.     if (*p_fcl != NUL)    /* can only be "all" right now */
  502.     {
  503.     checkupdate(curwin);
  504.     if (checkCloseRec(&curwin->w_folds, curwin->w_cursor.lnum,
  505.                             (int)curwin->w_p_fdl))
  506.         changed_window_setting();
  507.     }
  508. }
  509.  
  510. /* checkCloseRec() {{{2 */
  511.     static int
  512. checkCloseRec(gap, lnum, level)
  513.     garray_T    *gap;
  514.     linenr_T    lnum;
  515.     int        level;
  516. {
  517.     fold_T    *fp;
  518.     int        retval = FALSE;
  519.     int        i;
  520.  
  521.     fp = (fold_T *)gap->ga_data;
  522.     for (i = 0; i < gap->ga_len; ++i)
  523.     {
  524.     /* Only manually opened folds may need to be closed. */
  525.     if (fp[i].fd_flags == FD_OPEN)
  526.     {
  527.         if (level <= 0 && (lnum < fp[i].fd_top
  528.                       || lnum >= fp[i].fd_top + fp[i].fd_len))
  529.         {
  530.         fp[i].fd_flags = FD_LEVEL;
  531.         retval = TRUE;
  532.         }
  533.         else
  534.         retval |= checkCloseRec(&fp[i].fd_nested, lnum - fp[i].fd_top,
  535.                                    level - 1);
  536.     }
  537.     }
  538.     return retval;
  539. }
  540.  
  541. /* foldCreateAllowed() {{{2 */
  542. /*
  543.  * Return TRUE if it's allowed to manually create or delete a fold.
  544.  * Give an error message and return FALSE if not.
  545.  */
  546.     int
  547. foldManualAllowed(create)
  548.     int        create;
  549. {
  550.     if (foldmethodIsManual(curwin)
  551.            || (foldmethodIsMarker(curwin) && *curbuf->b_p_cms != NUL))
  552.     return TRUE;
  553.     if (create)
  554.     EMSG(_("E350: Cannot create fold with current 'foldmethod'"));
  555.     else
  556.     EMSG(_("E351: Cannot delete fold with current 'foldmethod'"));
  557.     return FALSE;
  558. }
  559.  
  560. /* foldCreate() {{{2 */
  561. /*
  562.  * Create a fold from line "start" to line "end" (inclusive) in the current
  563.  * window.
  564.  */
  565.     void
  566. foldCreate(start, end)
  567.     linenr_T    start;
  568.     linenr_T    end;
  569. {
  570.     fold_T    *fp;
  571.     garray_T    *gap;
  572.     garray_T    fold_ga;
  573.     int        i, j;
  574.     int        cont;
  575.     int        use_level = FALSE;
  576.     int        closed = FALSE;
  577.     int        level = 0;
  578.     linenr_T    start_rel = start;
  579.     linenr_T    end_rel = end;
  580.  
  581.     if (start > end)
  582.     {
  583.     /* reverse the range */
  584.     end = start_rel;
  585.     start = end_rel;
  586.     start_rel = start;
  587.     end_rel = end;
  588.     }
  589.  
  590.     /* When 'foldmethod' is "marker" add markers, which creates the folds. */
  591.     if (foldmethodIsMarker(curwin))
  592.     {
  593.     foldCreateMarkers(start, end);
  594.     return;
  595.     }
  596.  
  597.     checkupdate(curwin);
  598.  
  599.     /* Find the place to insert the new fold. */
  600.     gap = &curwin->w_folds;
  601.     for (;;)
  602.     {
  603.     if (!foldFind(gap, start_rel, &fp))
  604.         break;
  605.     if (fp->fd_top + fp->fd_len > end_rel)
  606.     {
  607.         /* New fold is completely inside this fold: Go one level deeper. */
  608.         gap = &fp->fd_nested;
  609.         start_rel -= fp->fd_top;
  610.         end_rel -= fp->fd_top;
  611.         if (use_level || fp->fd_flags == FD_LEVEL)
  612.         {
  613.         use_level = TRUE;
  614.         if (level >= curwin->w_p_fdl)
  615.             closed = TRUE;
  616.         }
  617.         else if (fp->fd_flags == FD_CLOSED)
  618.         closed = TRUE;
  619.         ++level;
  620.     }
  621.     else
  622.     {
  623.         /* This fold and new fold overlap: Insert here and move some folds
  624.          * inside the new fold. */
  625.         break;
  626.     }
  627.     }
  628.  
  629.     i = (int)(fp - (fold_T *)gap->ga_data);
  630.     if (ga_grow(gap, 1) == OK)
  631.     {
  632.     fp = (fold_T *)gap->ga_data + i;
  633.     ga_init2(&fold_ga, (int)sizeof(fold_T), 10);
  634.  
  635.     /* Count number of folds that will be contained in the new fold. */
  636.     for (cont = 0; i + cont < gap->ga_len; ++cont)
  637.         if (fp[cont].fd_top > end_rel)
  638.         break;
  639.     if (cont > 0 && ga_grow(&fold_ga, cont) == OK)
  640.     {
  641.         /* If the first fold starts before the new fold, let the new fold
  642.          * start there.  Otherwise the existing fold would change. */
  643.         if (start_rel > fp->fd_top)
  644.         start_rel = fp->fd_top;
  645.  
  646.         /* When last contained fold isn't completely contained, adjust end
  647.          * of new fold. */
  648.         if (end_rel < fp[cont - 1].fd_top + fp[cont - 1].fd_len - 1)
  649.         end_rel = fp[cont - 1].fd_top + fp[cont - 1].fd_len - 1;
  650.         /* Move contained folds to inside new fold. */
  651.         mch_memmove(fold_ga.ga_data, fp, sizeof(fold_T) * cont);
  652.         fold_ga.ga_len += cont;
  653.         fold_ga.ga_room -= cont;
  654.         i += cont;
  655.  
  656.         /* Adjust line numbers in contained folds to be relative to the
  657.          * new fold. */
  658.         for (j = 0; j < cont; ++j)
  659.         ((fold_T *)fold_ga.ga_data)[j].fd_top -= start_rel;
  660.     }
  661.     /* Move remaining entries to after the new fold. */
  662.     if (i < gap->ga_len)
  663.         mch_memmove(fp + 1, (fold_T *)gap->ga_data + i,
  664.                      sizeof(fold_T) * (gap->ga_len - i));
  665.     gap->ga_len = gap->ga_len + 1 - cont;
  666.     gap->ga_room = gap->ga_room - 1 + cont;
  667.  
  668.     /* insert new fold */
  669.     fp->fd_nested = fold_ga;
  670.     fp->fd_top = start_rel;
  671.     fp->fd_len = end_rel - start_rel + 1;
  672.  
  673.     /* We want the new fold to be closed.  If it would remain open because
  674.      * of using 'foldlevel', need to adjust fd_flags of containing folds.
  675.      */
  676.     if (use_level && !closed && level < curwin->w_p_fdl)
  677.         closeFold(start, 1L);
  678.     if (!use_level)
  679.         curwin->w_fold_manual = TRUE;
  680.     fp->fd_flags = FD_CLOSED;
  681.     fp->fd_small = MAYBE;
  682.  
  683.     /* redraw */
  684.     changed_window_setting();
  685.     }
  686. }
  687.  
  688. /* deleteFold() {{{2 */
  689. /*
  690.  * Delete a fold at line "start" in the current window.
  691.  * When "end" is not 0, delete all folds from "start" to "end".
  692.  * When "recursive" is TRUE delete recursively.
  693.  */
  694.     void
  695. deleteFold(start, end, recursive, had_visual)
  696.     linenr_T    start;
  697.     linenr_T    end;
  698.     int        recursive;
  699.     int        had_visual;    /* TRUE when Visual selection used */
  700. {
  701.     garray_T    *gap;
  702.     fold_T    *fp;
  703.     garray_T    *found_ga;
  704.     fold_T    *found_fp = NULL;
  705.     linenr_T    found_off = 0;
  706.     int        use_level = FALSE;
  707.     int        maybe_small = FALSE;
  708.     int        level = 0;
  709.     linenr_T    lnum = start;
  710.     linenr_T    lnum_off;
  711.     int        did_one = FALSE;
  712.     linenr_T    first_lnum = MAXLNUM;
  713.     linenr_T    last_lnum = 0;
  714.  
  715.     checkupdate(curwin);
  716.  
  717.     while (lnum <= end)
  718.     {
  719.     /* Find the deepest fold for "start". */
  720.     gap = &curwin->w_folds;
  721.     found_ga = NULL;
  722.     lnum_off = 0;
  723.     for (;;)
  724.     {
  725.         if (!foldFind(gap, lnum - lnum_off, &fp))
  726.         break;
  727.         /* lnum is inside this fold, remember info */
  728.         found_ga = gap;
  729.         found_fp = fp;
  730.         found_off = lnum_off;
  731.  
  732.         /* if "lnum" is folded, don't check nesting */
  733.         if (check_closed(curwin, fp, &use_level, level,
  734.                               &maybe_small, lnum_off))
  735.         break;
  736.  
  737.         /* check nested folds */
  738.         gap = &fp->fd_nested;
  739.         lnum_off += fp->fd_top;
  740.         ++level;
  741.     }
  742.     if (found_ga == NULL)
  743.     {
  744.         ++lnum;
  745.     }
  746.     else
  747.     {
  748.         lnum = found_fp->fd_top + found_fp->fd_len + found_off;
  749.         did_one = TRUE;
  750.  
  751.         if (foldmethodIsManual(curwin))
  752.         deleteFoldEntry(found_ga,
  753.             (int)(found_fp - (fold_T *)found_ga->ga_data), recursive);
  754.         else
  755.         {
  756.         if (found_fp->fd_top + found_off < first_lnum)
  757.             first_lnum = found_fp->fd_top;
  758.         if (lnum > last_lnum)
  759.             last_lnum = lnum;
  760.         parseMarker(curwin);
  761.         deleteFoldMarkers(found_fp, recursive, found_off);
  762.         }
  763.  
  764.         /* redraw window */
  765.         changed_window_setting();
  766.     }
  767.     }
  768.     if (!did_one)
  769.     {
  770.     EMSG(_(e_nofold));
  771. #ifdef FEAT_VISUAL
  772.     /* Force a redraw to remove the Visual highlighting. */
  773.     if (had_visual)
  774.         redraw_curbuf_later(INVERTED);
  775. #endif
  776.     }
  777.     if (last_lnum > 0)
  778.     changed_lines(first_lnum, (colnr_T)0, last_lnum, 0L);
  779. }
  780.  
  781. /* clearFolding() {{{2 */
  782. /*
  783.  * Remove all folding for window "win".
  784.  */
  785.     void
  786. clearFolding(win)
  787.     win_T    *win;
  788. {
  789.     deleteFoldRecurse(&win->w_folds);
  790.     win->w_foldinvalid = FALSE;
  791. }
  792.  
  793. /* foldUpdate() {{{2 */
  794. /*
  795.  * Update folds for changes in the buffer of a window.
  796.  * Note that inserted/deleted lines must have already been taken care of by
  797.  * calling foldMarkAdjust().
  798.  * The changes in lines from top to bot (inclusive).
  799.  */
  800.     void
  801. foldUpdate(wp, top, bot)
  802.     win_T    *wp;
  803.     linenr_T    top;
  804.     linenr_T    bot;
  805. {
  806.     fold_T    *fp;
  807.  
  808.     /* Mark all folds from top to bot as maybe-small. */
  809.     (void)foldFind(&curwin->w_folds, curwin->w_cursor.lnum, &fp);
  810.     while (fp < (fold_T *)curwin->w_folds.ga_data + curwin->w_folds.ga_len
  811.         && fp->fd_top < bot)
  812.     {
  813.     fp->fd_small = MAYBE;
  814.     ++fp;
  815.     }
  816.  
  817.     if (foldmethodIsIndent(wp)
  818.         || foldmethodIsExpr(wp)
  819.         || foldmethodIsMarker(wp)
  820. #ifdef FEAT_DIFF
  821.         || foldmethodIsDiff(wp)
  822. #endif
  823.         || foldmethodIsSyntax(wp))
  824.     foldUpdateIEMS(wp, top, bot);
  825. }
  826.  
  827. /* foldUpdateAll() {{{2 */
  828. /*
  829.  * Update all lines in the current window for folding.
  830.  * Used when a fold setting changes or after reloading the buffer.
  831.  * The actual updating is postponed until fold info is used, to avoid doing
  832.  * every time a setting is changed or a syntax item is added.
  833.  */
  834.     void
  835. foldUpdateAll(win)
  836.     win_T    *win;
  837. {
  838.     win->w_foldinvalid = TRUE;
  839. }
  840.  
  841. /* foldMoveTo() {{{2 */
  842. /*
  843.  * If "updown" is FALSE: Move to the start or end of the fold.
  844.  * If "updown" is TRUE: move to fold at the same level.
  845.  * If not moved return FAIL.
  846.  */
  847.     int
  848. foldMoveTo(updown, dir, count)
  849.     int        updown;
  850.     int        dir;        /* FORWARD or BACKWARD */
  851.     long    count;
  852. {
  853.     long    n;
  854.     int        retval = FAIL;
  855.     linenr_T    lnum_off;
  856.     linenr_T    lnum_found;
  857.     linenr_T    lnum;
  858.     int        use_level;
  859.     int        maybe_small;
  860.     garray_T    *gap;
  861.     fold_T    *fp;
  862.     int        level;
  863.     int        last;
  864.  
  865.     /* Repeat "count" times. */
  866.     for (n = 0; n < count; ++n)
  867.     {
  868.     /* Find nested folds.  Stop when a fold is closed.  The deepest fold
  869.      * that moves the cursor is used. */
  870.     lnum_off = 0;
  871.     gap = &curwin->w_folds;
  872.     use_level = FALSE;
  873.     maybe_small = FALSE;
  874.     lnum_found = curwin->w_cursor.lnum;
  875.     level = 0;
  876.     last = FALSE;
  877.     for (;;)
  878.     {
  879.         if (!foldFind(gap, curwin->w_cursor.lnum - lnum_off, &fp))
  880.         {
  881.         if (!updown)
  882.             break;
  883.  
  884.         /* When moving up, consider a fold above the cursor; when
  885.          * moving down consider a fold below the cursor. */
  886.         if (dir == FORWARD)
  887.         {
  888.             if (fp - (fold_T *)gap->ga_data >= gap->ga_len)
  889.             break;
  890.             --fp;
  891.         }
  892.         else
  893.         {
  894.             if (fp == (fold_T *)gap->ga_data)
  895.             break;
  896.         }
  897.         /* don't look for contained folds, they will always move
  898.          * the cursor too far. */
  899.         last = TRUE;
  900.         }
  901.  
  902.         if (!last)
  903.         {
  904.         /* Check if this fold is closed. */
  905.         if (check_closed(curwin, fp, &use_level, level,
  906.                               &maybe_small, lnum_off))
  907.             last = TRUE;
  908.  
  909.         /* "[z" and "]z" stop at closed fold */
  910.         if (last && !updown)
  911.             break;
  912.         }
  913.  
  914.         if (updown)
  915.         {
  916.         if (dir == FORWARD)
  917.         {
  918.             /* to start of next fold if there is one */
  919.             if (fp + 1 - (fold_T *)gap->ga_data < gap->ga_len)
  920.             {
  921.             lnum = fp[1].fd_top + lnum_off;
  922.             if (lnum > curwin->w_cursor.lnum)
  923.                 lnum_found = lnum;
  924.             }
  925.         }
  926.         else
  927.         {
  928.             /* to end of previous fold if there is one */
  929.             if (fp > (fold_T *)gap->ga_data)
  930.             {
  931.             lnum = fp[-1].fd_top + lnum_off + fp[-1].fd_len - 1;
  932.             if (lnum < curwin->w_cursor.lnum)
  933.                 lnum_found = lnum;
  934.             }
  935.         }
  936.         }
  937.         else
  938.         {
  939.         /* Open fold found, set cursor to its start/end and then check
  940.          * nested folds. */
  941.         if (dir == FORWARD)
  942.         {
  943.             lnum = fp->fd_top + lnum_off + fp->fd_len - 1;
  944.             if (lnum > curwin->w_cursor.lnum)
  945.             lnum_found = lnum;
  946.         }
  947.         else
  948.         {
  949.             lnum = fp->fd_top + lnum_off;
  950.             if (lnum < curwin->w_cursor.lnum)
  951.             lnum_found = lnum;
  952.         }
  953.         }
  954.  
  955.         if (last)
  956.         break;
  957.  
  958.         /* Check nested folds (if any). */
  959.         gap = &fp->fd_nested;
  960.         lnum_off += fp->fd_top;
  961.         ++level;
  962.     }
  963.     if (lnum_found != curwin->w_cursor.lnum)
  964.     {
  965.         curwin->w_cursor.lnum = lnum_found;
  966.         curwin->w_cursor.col = 0;
  967.         retval = OK;
  968.     }
  969.     else
  970.         break;
  971.     }
  972.  
  973.     return retval;
  974. }
  975.  
  976. /* foldInitWin() {{{2 */
  977. /*
  978.  * Init the fold info in a new window.
  979.  */
  980.     void
  981. foldInitWin(newwin)
  982.     win_T    *newwin;
  983. {
  984.     ga_init2(&newwin->w_folds, (int)sizeof(fold_T), 10);
  985. }
  986.  
  987. /* find_wl_entry() {{{2 */
  988. /*
  989.  * Find an entry in the win->w_lines[] array for buffer line "lnum".
  990.  * Only valid entries are considered (for entries where wl_valid is FALSE the
  991.  * line number can be wrong).
  992.  * Returns index of entry or -1 if not found.
  993.  */
  994.     int
  995. find_wl_entry(win, lnum)
  996.     win_T    *win;
  997.     linenr_T    lnum;
  998. {
  999.     int        i;
  1000.  
  1001.     if (win->w_lines_valid > 0)
  1002.     for (i = 0; i < win->w_lines_valid; ++i)
  1003.         if (win->w_lines[i].wl_valid)
  1004.         {
  1005.         if (lnum < win->w_lines[i].wl_lnum)
  1006.             return -1;
  1007.         if (lnum <= win->w_lines[i].wl_lastlnum)
  1008.             return i;
  1009.         }
  1010.     return -1;
  1011. }
  1012.  
  1013. /* foldAdjustVisual() {{{2 */
  1014. #ifdef FEAT_VISUAL
  1015. /*
  1016.  * Adjust the Visual area to include any fold at the start or end completely.
  1017.  */
  1018.     void
  1019. foldAdjustVisual()
  1020. {
  1021.     pos_T    *start, *end;
  1022.     char_u    *ptr;
  1023.  
  1024.     if (!VIsual_active || !hasAnyFolding(curwin))
  1025.     return;
  1026.  
  1027.     if (ltoreq(VIsual, curwin->w_cursor))
  1028.     {
  1029.     start = &VIsual;
  1030.     end = &curwin->w_cursor;
  1031.     }
  1032.     else
  1033.     {
  1034.     start = &curwin->w_cursor;
  1035.     end = &VIsual;
  1036.     }
  1037.     if (hasFolding(start->lnum, &start->lnum, NULL))
  1038.     start->col = 0;
  1039.     if (hasFolding(end->lnum, NULL, &end->lnum))
  1040.     {
  1041.     ptr = ml_get(end->lnum);
  1042.     end->col = (colnr_T)STRLEN(ptr);
  1043.     if (end->col > 0 && *p_sel == 'o')
  1044.         --end->col;
  1045. #ifdef FEAT_MBYTE
  1046.     /* prevent cursor from moving on the trail byte */
  1047.     if (has_mbyte)
  1048.         mb_adjust_cursor();
  1049. #endif
  1050.     }
  1051. }
  1052. #endif
  1053.  
  1054. /* cursor_foldstart() {{{2 */
  1055. /*
  1056.  * Move the cursor to the first line of a closed fold.
  1057.  */
  1058.     void
  1059. foldAdjustCursor()
  1060. {
  1061.     (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL);
  1062. }
  1063.  
  1064. /* Internal functions for "fold_T" {{{1 */
  1065. /* cloneFoldGrowArray() {{{2 */
  1066. /*
  1067.  * Will "clone" (i.e deep copy) a garray_T of folds.
  1068.  *
  1069.  * Return FAIL if the operation cannot be completed, otherwise OK.
  1070.  */
  1071.     void
  1072. cloneFoldGrowArray(from, to)
  1073.     garray_T    *from;
  1074.     garray_T    *to;
  1075. {
  1076.     int        i;
  1077.     fold_T    *from_p;
  1078.     fold_T    *to_p;
  1079.  
  1080.     ga_init2(to, from->ga_itemsize, from->ga_growsize);
  1081.     if (from->ga_len == 0 || ga_grow(to, from->ga_len) == FAIL)
  1082.     return;
  1083.  
  1084.     from_p = (fold_T *)from->ga_data;
  1085.     to_p = (fold_T *)to->ga_data;
  1086.  
  1087.     for (i = 0; i < from->ga_len; i++)
  1088.     {
  1089.     to_p->fd_top = from_p->fd_top;
  1090.     to_p->fd_len = from_p->fd_len;
  1091.     to_p->fd_flags = from_p->fd_flags;
  1092.     to_p->fd_small = from_p->fd_small;
  1093.     cloneFoldGrowArray(&from_p->fd_nested, &to_p->fd_nested);
  1094.     ++to->ga_len;
  1095.     --to->ga_room;
  1096.     ++from_p;
  1097.     ++to_p;
  1098.     }
  1099. }
  1100.  
  1101. /* foldFind() {{{2 */
  1102. /*
  1103.  * Search for line "lnum" in folds of growarray "gap".
  1104.  * Set *fpp to the fold struct for the fold that contains "lnum" or
  1105.  * the first fold below it (careful: it can be beyond the end of the array!).
  1106.  * Returns FALSE when there is no fold that contains "lnum".
  1107.  */
  1108.     static int
  1109. foldFind(gap, lnum, fpp)
  1110.     garray_T    *gap;
  1111.     linenr_T    lnum;
  1112.     fold_T    **fpp;
  1113. {
  1114.     linenr_T    low, high;
  1115.     fold_T    *fp;
  1116.     int        i;
  1117.  
  1118.     /*
  1119.      * Perform a binary search.
  1120.      * "low" is lowest index of possible match.
  1121.      * "high" is highest index of possible match.
  1122.      */
  1123.     fp = (fold_T *)gap->ga_data;
  1124.     low = 0;
  1125.     high = gap->ga_len - 1;
  1126.     while (low <= high)
  1127.     {
  1128.     i = (low + high) / 2;
  1129.     if (fp[i].fd_top > lnum)
  1130.         /* fold below lnum, adjust high */
  1131.         high = i - 1;
  1132.     else if (fp[i].fd_top + fp[i].fd_len <= lnum)
  1133.         /* fold above lnum, adjust low */
  1134.         low = i + 1;
  1135.     else
  1136.     {
  1137.         /* lnum is inside this fold */
  1138.         *fpp = fp + i;
  1139.         return TRUE;
  1140.     }
  1141.     }
  1142.     *fpp = fp + low;
  1143.     return FALSE;
  1144. }
  1145.  
  1146. /* foldLevelWin() {{{2 */
  1147. /*
  1148.  * Return fold level at line number "lnum" in window "wp".
  1149.  */
  1150.     static int
  1151. foldLevelWin(wp, lnum)
  1152.     win_T    *wp;
  1153.     linenr_T    lnum;
  1154. {
  1155.     fold_T    *fp;
  1156.     linenr_T    lnum_rel = lnum;
  1157.     int        level =  0;
  1158.     garray_T    *gap;
  1159.  
  1160.     /* Recursively search for a fold that contains "lnum". */
  1161.     gap = &wp->w_folds;
  1162.     for (;;)
  1163.     {
  1164.     if (!foldFind(gap, lnum_rel, &fp))
  1165.         break;
  1166.     /* Check nested folds.  Line number is relative to containing fold. */
  1167.     gap = &fp->fd_nested;
  1168.     lnum_rel -= fp->fd_top;
  1169.     ++level;
  1170.     }
  1171.  
  1172.     return level;
  1173. }
  1174.  
  1175. /* checkupdate() {{{2 */
  1176. /*
  1177.  * Check if the folds in window "wp" are invalid and update them if needed.
  1178.  */
  1179.     static void
  1180. checkupdate(wp)
  1181.     win_T    *wp;
  1182. {
  1183.     if (wp->w_foldinvalid)
  1184.     {
  1185.     foldUpdate(wp, (linenr_T)1, (linenr_T)MAXLNUM); /* will update all */
  1186.     wp->w_foldinvalid = FALSE;
  1187.     }
  1188. }
  1189.  
  1190. /* setFoldRepeat() {{{2 */
  1191. /*
  1192.  * Open or close fold for current window at line "lnum".
  1193.  * Repeat "count" times.
  1194.  */
  1195.     static void
  1196. setFoldRepeat(lnum, count, open)
  1197.     linenr_T    lnum;
  1198.     long    count;
  1199.     int        open;
  1200. {
  1201.     int        done;
  1202.     long    n;
  1203.  
  1204.     for (n = 0; n < count; ++n)
  1205.     {
  1206.     done = DONE_NOTHING;
  1207.     (void)setManualFold(lnum, open, FALSE, &done);
  1208.     if (!(done & DONE_ACTION))
  1209.     {
  1210.         /* Only give an error message when no fold could be opened. */
  1211.         if (n == 0 && !(done & DONE_FOLD))
  1212.         EMSG(_(e_nofold));
  1213.         break;
  1214.     }
  1215.     }
  1216. }
  1217.  
  1218. /* setManualFold() {{{2 */
  1219. /*
  1220.  * Open or close the fold in the current window which contains "lnum".
  1221.  * "donep", when not NULL, points to flag that is set to DONE_FOLD when some
  1222.  * fold was found and to DONE_ACTION when some fold was opened or closed.
  1223.  * When "donep" is NULL give an error message when no fold was found for
  1224.  * "lnum".
  1225.  * Return the line number of the next line that could be closed.
  1226.  * It's only valid when "opening" is TRUE!
  1227.  */
  1228.     static linenr_T
  1229. setManualFold(lnum, opening, recurse, donep)
  1230.     linenr_T    lnum;
  1231.     int        opening;    /* TRUE when opening, FALSE when closing */
  1232.     int        recurse;    /* TRUE when closing/opening recursive */
  1233.     int        *donep;
  1234. {
  1235.     fold_T    *fp;
  1236.     fold_T    *fp2;
  1237.     fold_T    *found = NULL;
  1238.     int        j;
  1239.     int        level = 0;
  1240.     int        use_level = FALSE;
  1241.     int        found_fold = FALSE;
  1242.     garray_T    *gap;
  1243.     linenr_T    next = MAXLNUM;
  1244.     linenr_T    off = 0;
  1245.     int        done = 0;
  1246.  
  1247.     checkupdate(curwin);
  1248.  
  1249.     /*
  1250.      * Find the fold, open or close it.
  1251.      */
  1252.     gap = &curwin->w_folds;
  1253.     for (;;)
  1254.     {
  1255.     if (!foldFind(gap, lnum, &fp))
  1256.     {
  1257.         /* If there is a following fold, continue there next time. */
  1258.         if (fp < (fold_T *)gap->ga_data + gap->ga_len)
  1259.         next = fp->fd_top + off;
  1260.         break;
  1261.     }
  1262.  
  1263.     /* lnum is inside this fold */
  1264.     found_fold = TRUE;
  1265.  
  1266.     /* If there is a following fold, continue there next time. */
  1267.     if (fp + 1 < (fold_T *)gap->ga_data + gap->ga_len)
  1268.         next = fp[1].fd_top + off;
  1269.  
  1270.     /* Change from level-dependent folding to manual. */
  1271.     if (use_level || fp->fd_flags == FD_LEVEL)
  1272.     {
  1273.         use_level = TRUE;
  1274.         if (level >= curwin->w_p_fdl)
  1275.         fp->fd_flags = FD_CLOSED;
  1276.         else
  1277.         fp->fd_flags = FD_OPEN;
  1278.         fp2 = (fold_T *)fp->fd_nested.ga_data;
  1279.         for (j = 0; j < fp->fd_nested.ga_len; ++j)
  1280.         fp2[j].fd_flags = FD_LEVEL;
  1281.     }
  1282.  
  1283.     /* Simple case: Close recursively means closing the fold. */
  1284.     if (!opening && recurse)
  1285.     {
  1286.         if (fp->fd_flags != FD_CLOSED)
  1287.         {
  1288.         done |= DONE_ACTION;
  1289.         fp->fd_flags = FD_CLOSED;
  1290.         }
  1291.     }
  1292.     else if (fp->fd_flags == FD_CLOSED)
  1293.     {
  1294.         /* When opening, open topmost closed fold. */
  1295.         if (opening)
  1296.         {
  1297.         fp->fd_flags = FD_OPEN;
  1298.         done |= DONE_ACTION;
  1299.         if (recurse)
  1300.             foldOpenNested(fp);
  1301.         }
  1302.         break;
  1303.     }
  1304.  
  1305.     /* fold is open, check nested folds */
  1306.     found = fp;
  1307.     gap = &fp->fd_nested;
  1308.     lnum -= fp->fd_top;
  1309.     off += fp->fd_top;
  1310.     ++level;
  1311.     }
  1312.     if (found_fold)
  1313.     {
  1314.     /* When closing and not recurse, close deepest open fold. */
  1315.     if (!opening && found != NULL)
  1316.     {
  1317.         found->fd_flags = FD_CLOSED;
  1318.         done |= DONE_ACTION;
  1319.     }
  1320.     curwin->w_fold_manual = TRUE;
  1321.     if (done & DONE_ACTION)
  1322.         changed_window_setting();
  1323.     done |= DONE_FOLD;
  1324.     }
  1325.     else if (donep == NULL)
  1326.     EMSG(_(e_nofold));
  1327.  
  1328.     if (donep != NULL)
  1329.     *donep |= done;
  1330.  
  1331.     return next;
  1332. }
  1333.  
  1334. /* foldOpenNested() {{{2 */
  1335. /*
  1336.  * Open all nested folds in fold "fpr" recursively.
  1337.  */
  1338.     static void
  1339. foldOpenNested(fpr)
  1340.     fold_T    *fpr;
  1341. {
  1342.     int        i;
  1343.     fold_T    *fp;
  1344.  
  1345.     fp = (fold_T *)fpr->fd_nested.ga_data;
  1346.     for (i = 0; i < fpr->fd_nested.ga_len; ++i)
  1347.     {
  1348.     foldOpenNested(&fp[i]);
  1349.     fp[i].fd_flags = FD_OPEN;
  1350.     }
  1351. }
  1352.  
  1353. /* deleteFoldEntry() {{{2 */
  1354. /*
  1355.  * Delete fold "idx" from growarray "gap".
  1356.  * When "recursive" is TRUE also delete all the folds contained in it.
  1357.  * When "recursive" is FALSE contained folds are moved one level up.
  1358.  */
  1359.     static void
  1360. deleteFoldEntry(gap, idx, recursive)
  1361.     garray_T    *gap;
  1362.     int        idx;
  1363.     int        recursive;
  1364. {
  1365.     fold_T    *fp;
  1366.     int        i;
  1367.     long    moved;
  1368.     fold_T    *nfp;
  1369.  
  1370.     fp = (fold_T *)gap->ga_data + idx;
  1371.     if (recursive || fp->fd_nested.ga_len == 0)
  1372.     {
  1373.     /* recursively delete the contained folds */
  1374.     deleteFoldRecurse(&fp->fd_nested);
  1375.     --gap->ga_len;
  1376.     ++gap->ga_room;
  1377.     if (idx < gap->ga_len)
  1378.         mch_memmove(fp, fp + 1, sizeof(fold_T) * (gap->ga_len - idx));
  1379.     }
  1380.     else
  1381.     {
  1382.     /* move nested folds one level up, to overwrite the fold that is
  1383.      * deleted. */
  1384.     moved = fp->fd_nested.ga_len;
  1385.     if (ga_grow(gap, (int)(moved - 1)) == OK)
  1386.     {
  1387.         /* adjust fd_top and fd_flags for the moved folds */
  1388.         nfp = (fold_T *)fp->fd_nested.ga_data;
  1389.         for (i = 0; i < moved; ++i)
  1390.         {
  1391.         nfp[i].fd_top += fp->fd_top;
  1392.         if (fp->fd_flags == FD_LEVEL)
  1393.             nfp[i].fd_flags = FD_LEVEL;
  1394.         if (fp->fd_small == MAYBE)
  1395.             nfp[i].fd_small = MAYBE;
  1396.         }
  1397.  
  1398.         /* move the existing folds down to make room */
  1399.         if (idx < gap->ga_len)
  1400.         mch_memmove(fp + moved, fp + 1,
  1401.                     sizeof(fold_T) * (gap->ga_len - idx));
  1402.         /* move the contained folds one level up */
  1403.         mch_memmove(fp, nfp, (size_t)(sizeof(fold_T) * moved));
  1404.         vim_free(nfp);
  1405.         gap->ga_len += moved - 1;
  1406.         gap->ga_room -= moved - 1;
  1407.     }
  1408.     }
  1409. }
  1410.  
  1411. /* deleteFoldRecurse() {{{2 */
  1412. /*
  1413.  * Delete nested folds in a fold.
  1414.  */
  1415.     void
  1416. deleteFoldRecurse(gap)
  1417.     garray_T    *gap;
  1418. {
  1419.     int        i;
  1420.  
  1421.     for (i = 0; i < gap->ga_len; ++i)
  1422.     deleteFoldRecurse(&(((fold_T *)(gap->ga_data))[i].fd_nested));
  1423.     ga_clear(gap);
  1424. }
  1425.  
  1426. /* foldMarkAdjust() {{{2 */
  1427. /*
  1428.  * Update line numbers of folds for inserted/deleted lines.
  1429.  */
  1430.     void
  1431. foldMarkAdjust(wp, line1, line2, amount, amount_after)
  1432.     win_T    *wp;
  1433.     linenr_T    line1;
  1434.     linenr_T    line2;
  1435.     long    amount;
  1436.     long    amount_after;
  1437. {
  1438.     /* If deleting marks from line1 to line2, but not deleting all those
  1439.      * lines, set line2 so that only deleted lines have their folds removed. */
  1440.     if (amount == MAXLNUM && line2 >= line1 && line2 - line1 >= -amount_after)
  1441.     line2 = line1 - amount_after - 1;
  1442.     /* If appending a line in Insert mode, it should be included in the fold
  1443.      * just above the line. */
  1444.     if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM)
  1445.     --line1;
  1446.     foldMarkAdjustRecurse(&wp->w_folds, line1, line2, amount, amount_after);
  1447. }
  1448.  
  1449. /* foldMarkAdjustRecurse() {{{2 */
  1450.     static void
  1451. foldMarkAdjustRecurse(gap, line1, line2, amount, amount_after)
  1452.     garray_T    *gap;
  1453.     linenr_T    line1;
  1454.     linenr_T    line2;
  1455.     long    amount;
  1456.     long    amount_after;
  1457. {
  1458.     fold_T    *fp;
  1459.     int        i;
  1460.     linenr_T    last;
  1461.     linenr_T    top;
  1462.  
  1463.     /* In Insert mode an inserted line at the top of a fold is considered part
  1464.      * of the fold, otherwise it isn't. */
  1465.     if ((State & INSERT) && amount == (linenr_T)1 && line2 == MAXLNUM)
  1466.     top = line1 + 1;
  1467.     else
  1468.     top = line1;
  1469.  
  1470.     /* Find the fold containing or just below "line1". */
  1471.     (void)foldFind(gap, line1, &fp);
  1472.  
  1473.     /*
  1474.      * Adjust all folds below "line1" that are affected.
  1475.      */
  1476.     for (i = (int)(fp - (fold_T *)gap->ga_data); i < gap->ga_len; ++i, ++fp)
  1477.     {
  1478.     /*
  1479.      * Check for these situations:
  1480.      *      1  2    3
  1481.      *      1  2    3
  1482.      * line1     2    3  4  5
  1483.      *         2    3  4  5
  1484.      *         2    3  4  5
  1485.      * line2     2    3  4  5
  1486.      *        3     5  6
  1487.      *        3     5  6
  1488.      */
  1489.  
  1490.     last = fp->fd_top + fp->fd_len - 1; /* last line of fold */
  1491.  
  1492.     /* 1. fold completely above line1: nothing to do */
  1493.     if (last < line1)
  1494.         continue;
  1495.  
  1496.     /* 6. fold below line2: only adjust for amount_after */
  1497.     if (fp->fd_top > line2)
  1498.     {
  1499.         if (amount_after == 0)
  1500.         break;
  1501.         fp->fd_top += amount_after;
  1502.     }
  1503.     else
  1504.     {
  1505.         if (fp->fd_top >= top && last <= line2)
  1506.         {
  1507.         /* 4. fold completely contained in range */
  1508.         if (amount == MAXLNUM)
  1509.         {
  1510.             /* Deleting lines: delete the fold completely */
  1511.             deleteFoldEntry(gap, i, TRUE);
  1512.             --i;    /* adjust index for deletion */
  1513.             --fp;
  1514.         }
  1515.         else
  1516.             fp->fd_top += amount;
  1517.         }
  1518.         else
  1519.         {
  1520.         /* 2, 3, or 5: need to correct nested folds too */
  1521.         foldMarkAdjustRecurse(&fp->fd_nested, line1 - fp->fd_top,
  1522.                   line2 - fp->fd_top, amount, amount_after);
  1523.         if (fp->fd_top < top)
  1524.         {
  1525.             if (last <= line2)
  1526.             {
  1527.             /* 2. fold contains line1, line2 is below fold */
  1528.             if (amount == MAXLNUM)
  1529.                 fp->fd_len = line1 - fp->fd_top;
  1530.             else
  1531.                 fp->fd_len += amount;
  1532.             }
  1533.             else
  1534.             {
  1535.             /* 3. fold contains line1 and line2 */
  1536.             fp->fd_len += amount_after;
  1537.             }
  1538.         }
  1539.         else
  1540.         {
  1541.             /* 5. fold is below line1 and contains line2 */
  1542.             if (amount == MAXLNUM)
  1543.             {
  1544.             fp->fd_len -= line2 - fp->fd_top + 1;
  1545.             fp->fd_top = line1;
  1546.             }
  1547.             else
  1548.             {
  1549.             fp->fd_len += amount_after - amount;
  1550.             fp->fd_top += amount;
  1551.             }
  1552.         }
  1553.         }
  1554.     }
  1555.     }
  1556. }
  1557.  
  1558. /* getDeepestNesting() {{{2 */
  1559. /*
  1560.  * Get the lowest 'foldlevel' value that makes the deepest nested fold in the
  1561.  * current window open.
  1562.  */
  1563.     int
  1564. getDeepestNesting()
  1565. {
  1566.     checkupdate(curwin);
  1567.     return getDeepestNestingRecurse(&curwin->w_folds);
  1568. }
  1569.  
  1570.     static int
  1571. getDeepestNestingRecurse(gap)
  1572.     garray_T    *gap;
  1573. {
  1574.     int        i;
  1575.     int        level;
  1576.     int        maxlevel = 0;
  1577.     fold_T    *fp;
  1578.  
  1579.     fp = (fold_T *)gap->ga_data;
  1580.     for (i = 0; i < gap->ga_len; ++i)
  1581.     {
  1582.     level = getDeepestNestingRecurse(&fp[i].fd_nested) + 1;
  1583.     if (level > maxlevel)
  1584.         maxlevel = level;
  1585.     }
  1586.  
  1587.     return maxlevel;
  1588. }
  1589.  
  1590. /* check_closed() {{{2 */
  1591. /*
  1592.  * Check if a fold is closed and update the info needed to check nested folds.
  1593.  */
  1594.     static int
  1595. check_closed(win, fp, use_levelp, level, maybe_smallp, lnum_off)
  1596.     win_T    *win;
  1597.     fold_T    *fp;
  1598.     int        *use_levelp;        /* TRUE: outer fold had FD_LEVEL */
  1599.     int        level;            /* folding depth */
  1600.     int        *maybe_smallp;        /* TRUE: outer this had fd_small == MAYBE */
  1601.     linenr_T    lnum_off;        /* line number offset for fp->fd_top */
  1602. {
  1603.     int        closed = FALSE;
  1604.  
  1605.     /* Check if this fold is closed.  If the flag is FD_LEVEL this
  1606.      * fold and all folds it contains depend on 'foldlevel'. */
  1607.     if (*use_levelp || fp->fd_flags == FD_LEVEL)
  1608.     {
  1609.     *use_levelp = TRUE;
  1610.     if (level >= win->w_p_fdl)
  1611.         closed = TRUE;
  1612.     }
  1613.     else if (fp->fd_flags == FD_CLOSED)
  1614.     closed = TRUE;
  1615.  
  1616.     /* Small fold isn't closed anyway. */
  1617.     if (fp->fd_small == MAYBE)
  1618.     *maybe_smallp = TRUE;
  1619.     if (closed)
  1620.     {
  1621.     if (*maybe_smallp)
  1622.         fp->fd_small = MAYBE;
  1623.     checkSmall(win, fp, lnum_off);
  1624.     if (fp->fd_small == TRUE)
  1625.         closed = FALSE;
  1626.     }
  1627.     return closed;
  1628. }
  1629.  
  1630. /* checkSmall() {{{2 */
  1631. /*
  1632.  * Update fd_small field of fold "fp".
  1633.  */
  1634.     static void
  1635. checkSmall(wp, fp, lnum_off)
  1636.     win_T    *wp;
  1637.     fold_T    *fp;
  1638.     linenr_T    lnum_off;    /* offset for fp->fd_top */
  1639. {
  1640.     int        count;
  1641.     int        n;
  1642.  
  1643.     if (fp->fd_small == MAYBE)
  1644.     {
  1645.     /* Mark any nested folds to maybe-small */
  1646.     setSmallMaybe(&fp->fd_nested);
  1647.  
  1648.     if (fp->fd_len > curwin->w_p_fml)
  1649.         fp->fd_small = FALSE;
  1650.     else
  1651.     {
  1652.         count = 0;
  1653.         for (n = 0; n < fp->fd_len; ++n)
  1654.         {
  1655.         count += plines_win_nofold(wp, fp->fd_top + lnum_off + n);
  1656.         if (count > curwin->w_p_fml)
  1657.         {
  1658.             fp->fd_small = FALSE;
  1659.             return;
  1660.         }
  1661.         }
  1662.         fp->fd_small = TRUE;
  1663.     }
  1664.     }
  1665. }
  1666.  
  1667. /* setSmallMaybe() {{{2 */
  1668. /*
  1669.  * Set small flags in "gap" to MAYBE.
  1670.  */
  1671.     static void
  1672. setSmallMaybe(gap)
  1673.     garray_T    *gap;
  1674. {
  1675.     int        i;
  1676.     fold_T    *fp;
  1677.  
  1678.     fp = (fold_T *)gap->ga_data;
  1679.     for (i = 0; i < gap->ga_len; ++i)
  1680.     fp[i].fd_small = MAYBE;
  1681. }
  1682.  
  1683. /* foldCreateMarkers() {{{2 */
  1684. /*
  1685.  * Create a fold from line "start" to line "end" (inclusive) in the current
  1686.  * window by adding markers.
  1687.  */
  1688.     static void
  1689. foldCreateMarkers(start, end)
  1690.     linenr_T    start;
  1691.     linenr_T    end;
  1692. {
  1693.     if (!curbuf->b_p_ma)
  1694.     {
  1695.     EMSG(_(e_modifiable));
  1696.     return;
  1697.     }
  1698.     if (*curbuf->b_p_cms == NUL)
  1699.     {
  1700.     EMSG(_("E221: 'commentstring' is empty"));
  1701.     return;
  1702.     }
  1703.     parseMarker(curwin);
  1704.  
  1705.     foldAddMarker(start, curwin->w_p_fmr, foldstartmarkerlen);
  1706.     foldAddMarker(end, foldendmarker, foldendmarkerlen);
  1707.  
  1708.     /* Update both changes here, to avoid all folds after the start are
  1709.      * changed when the start marker is inserted and the end isn't. */
  1710.     changed_lines(start, (colnr_T)0, end, 0L);
  1711. }
  1712.  
  1713. /* foldAddMarker() {{{2 */
  1714. /*
  1715.  * Add "marker[markerlen]" in 'commentstring' to line "lnum".
  1716.  */
  1717.     static void
  1718. foldAddMarker(lnum, marker, markerlen)
  1719.     linenr_T    lnum;
  1720.     char_u    *marker;
  1721.     int        markerlen;
  1722. {
  1723.     char_u    *cms = curbuf->b_p_cms;
  1724.     char_u    *line;
  1725.     int        line_len;
  1726.     char_u    *newline;
  1727.     char_u    *p = (char_u *)strstr((char *)curbuf->b_p_cms, "%s");
  1728.  
  1729.     /* Allocate a new line: old-line + 'cms'-start + marker + 'cms'-end */
  1730.     line = ml_get(lnum);
  1731.     line_len = (int)STRLEN(line);
  1732.     newline = alloc((unsigned)(line_len + markerlen + STRLEN(cms) - 1));
  1733.     if (newline == NULL)
  1734.     return;
  1735.  
  1736.     if (u_save(lnum - 1, lnum + 1) == OK)
  1737.     {
  1738.     STRCPY(newline, line);
  1739.     STRCPY(newline + line_len, cms);
  1740.     STRNCPY(newline + line_len + (p - cms), marker, markerlen);
  1741.     STRCPY(newline + line_len + (p - cms) + markerlen, p + 2);
  1742.  
  1743.     ml_replace(lnum, newline, FALSE);
  1744.     }
  1745. }
  1746.  
  1747. /* deleteFoldMarkers() {{{2 */
  1748. /*
  1749.  * Delete the markers for a fold, causing it to be deleted.
  1750.  */
  1751.     static void
  1752. deleteFoldMarkers(fp, recursive, lnum_off)
  1753.     fold_T    *fp;
  1754.     int        recursive;
  1755.     linenr_T    lnum_off;    /* offset for fp->fd_top */
  1756. {
  1757.     int        i;
  1758.  
  1759.     if (recursive)
  1760.     for (i = 0; i < fp->fd_nested.ga_len; ++i)
  1761.         deleteFoldMarkers((fold_T *)fp->fd_nested.ga_data + i, TRUE,
  1762.                                lnum_off + fp->fd_top);
  1763.     foldDelMarker(fp->fd_top + lnum_off, curwin->w_p_fmr, foldstartmarkerlen);
  1764.     foldDelMarker(fp->fd_top + lnum_off + fp->fd_len - 1,
  1765.                          foldendmarker, foldendmarkerlen);
  1766. }
  1767.  
  1768. /* foldDelMarker() {{{2 */
  1769. /*
  1770.  * Delete marker "marker[markerlen]" at the end of line "lnum".
  1771.  * Delete 'commentstring' if it matches.
  1772.  * If the marker is not found, there is no error message.  Could a missing
  1773.  * close-marker.
  1774.  */
  1775.     static void
  1776. foldDelMarker(lnum, marker, markerlen)
  1777.     linenr_T    lnum;
  1778.     char_u    *marker;
  1779.     int        markerlen;
  1780. {
  1781.     char_u    *line;
  1782.     char_u    *newline;
  1783.     char_u    *p;
  1784.     int        len;
  1785.     char_u    *cms = curbuf->b_p_cms;
  1786.     char_u    *cms2;
  1787.  
  1788.     line = ml_get(lnum);
  1789.     for (p = line; *p != NUL; ++p)
  1790.     if (STRNCMP(p, marker, markerlen) == 0)
  1791.     {
  1792.         /* Found the marker, include a digit if it's there. */
  1793.         len = markerlen;
  1794.         if (isdigit(p[len]))
  1795.         ++len;
  1796.         if (*cms != NUL)
  1797.         {
  1798.         /* Also delete 'commentstring' if it matches. */
  1799.         cms2 = (char_u *)strstr((char *)cms, "%s");
  1800.         if (p - line >= cms2 - cms
  1801.             && STRNCMP(p - (cms2 - cms), cms, cms2 - cms) == 0
  1802.             && STRNCMP(p + len, cms2 + 2, STRLEN(cms2 + 2)) == 0)
  1803.         {
  1804.             p -= cms2 - cms;
  1805.             len += (int)STRLEN(cms) - 2;
  1806.         }
  1807.         }
  1808.         if (u_save(lnum - 1, lnum + 1) == OK)
  1809.         {
  1810.         /* Make new line: text-before-marker + text-after-marker */
  1811.         newline = alloc((unsigned)(STRLEN(line) - len + 1));
  1812.         if (newline != NULL)
  1813.         {
  1814.             STRNCPY(newline, line, p - line);
  1815.             STRCPY(newline + (p - line), p + len);
  1816.             ml_replace(lnum, newline, FALSE);
  1817.         }
  1818.         }
  1819.         break;
  1820.     }
  1821. }
  1822.  
  1823. /* foldtext_cleanup() {{{2 */
  1824. /*
  1825.  * Remove 'foldmarker' and 'commentstring' from "str" (in-place).
  1826.  */
  1827.     void
  1828. foldtext_cleanup(str)
  1829.     char_u    *str;
  1830. {
  1831.     char_u    *cms_start;    /* first part or the whole comment */
  1832.     int        cms_slen = 0;    /* length of cms_start */
  1833.     char_u    *cms_end;    /* last part of the comment or NULL */
  1834.     int        cms_elen = 0;    /* length of cms_end */
  1835.     char_u    *s;
  1836.     int        len;
  1837.     int        did1 = FALSE;
  1838.     int        did2 = FALSE;
  1839.  
  1840.     /* Ignore leading and trailing white space in 'commentstring'. */
  1841.     cms_start = skipwhite(curbuf->b_p_cms);
  1842.     cms_slen = STRLEN(cms_start);
  1843.     while (cms_slen > 0 && vim_iswhite(cms_start[cms_slen - 1]))
  1844.     --cms_slen;
  1845.  
  1846.     /* locate "%s" in 'commentstring', use the part before and after it. */
  1847.     cms_end = (char_u *)strstr((char *)cms_start, "%s");
  1848.     if (cms_end != NULL)
  1849.     {
  1850.     cms_elen = cms_slen - (cms_end - cms_start);
  1851.     cms_slen = cms_end - cms_start;
  1852.  
  1853.     /* exclude white space before "%s" */
  1854.     while (cms_slen > 0 && vim_iswhite(cms_start[cms_slen - 1]))
  1855.         --cms_slen;
  1856.  
  1857.     /* skip "%s" and white space after it */
  1858.     s = skipwhite(cms_end + 2);
  1859.     cms_elen -= s - cms_end;
  1860.     cms_end = s;
  1861.     }
  1862.     parseMarker(curwin);
  1863.  
  1864.     for (s = str; *s != NUL; )
  1865.     {
  1866.     len = 0;
  1867.     if (STRNCMP(s, curwin->w_p_fmr, foldstartmarkerlen) == 0)
  1868.     {
  1869.         len = foldstartmarkerlen;
  1870.         if (isdigit(s[len]))
  1871.         ++len;
  1872.     }
  1873.     else if (STRNCMP(s, foldendmarker, foldendmarkerlen) == 0)
  1874.     {
  1875.         len = foldendmarkerlen;
  1876.         if (isdigit(s[len]))
  1877.         ++len;
  1878.     }
  1879.     else if (cms_end != NULL)
  1880.     {
  1881.         if (!did1 && STRNCMP(s, cms_start, cms_slen) == 0)
  1882.         {
  1883.         len = cms_slen;
  1884.         did1 = TRUE;
  1885.         }
  1886.         else if (!did2 && STRNCMP(s, cms_end, cms_elen) == 0)
  1887.         {
  1888.         len = cms_elen;
  1889.         did2 = TRUE;
  1890.         }
  1891.     }
  1892.     if (len != 0)
  1893.     {
  1894.         while (vim_iswhite(s[len]))
  1895.         ++len;
  1896.         mch_memmove(s, s + len, STRLEN(s + len) + 1);
  1897.     }
  1898.     else
  1899.     {
  1900. #ifdef FEAT_MBYTE
  1901.         if (has_mbyte)
  1902.         s += (*mb_ptr2len_check)(s);
  1903.         else
  1904. #endif
  1905.         ++s;
  1906.     }
  1907.     }
  1908. }
  1909.  
  1910. /* Folding by indent, expr, marker and syntax. {{{1 */
  1911. /* Define "fline_T", passed to get fold level for a line. {{{2 */
  1912. typedef struct
  1913. {
  1914.     win_T    *wp;        /* window */
  1915.     linenr_T    lnum;        /* current line number */
  1916.     linenr_T    off;        /* offset between lnum and real line number */
  1917.     linenr_T    lnum_save;    /* line nr used by foldUpdateIEMSRecurse() */
  1918.     int        lvl;        /* current level (-1 for undefined) */
  1919.     int        lvl_next;    /* level used for next line */
  1920.     int        start;        /* number of folds that are forced to start at
  1921.                    this line. */
  1922.     int        end;        /* level of fold that is forced to end below
  1923.                    this line */
  1924.     int        had_end;    /* level of fold that is forced to end above
  1925.                    this line (copy of "end" of prev. line) */
  1926. } fline_T;
  1927.  
  1928. /* Flag is set when redrawing is needed. */
  1929. static int fold_changed;
  1930.  
  1931. /* Function declarations. {{{2 */
  1932. static linenr_T foldUpdateIEMSRecurse __ARGS((garray_T *gap, int level, linenr_T startlnum, fline_T *flp, void (*getlevel)__ARGS((fline_T *)), linenr_T bot, int topflags));
  1933. static int foldInsert __ARGS((garray_T *gap, int i));
  1934. static void foldSplit __ARGS((garray_T *gap, int i, linenr_T top, linenr_T bot));
  1935. static void foldRemove __ARGS((garray_T *gap, linenr_T top, linenr_T bot));
  1936. static void foldMerge __ARGS((fold_T *fp1, garray_T *gap, fold_T *fp2));
  1937. static void foldlevelIndent __ARGS((fline_T *flp));
  1938. #ifdef FEAT_DIFF
  1939. static void foldlevelDiff __ARGS((fline_T *flp));
  1940. #endif
  1941. static void foldlevelExpr __ARGS((fline_T *flp));
  1942. static void foldlevelMarker __ARGS((fline_T *flp));
  1943. static void foldlevelSyntax __ARGS((fline_T *flp));
  1944.  
  1945. /* foldUpdateIEMS() {{{2 */
  1946. /*
  1947.  * Update the folding for window "wp", at least from lines "top" to "bot".
  1948.  * Return TRUE if any folds did change.
  1949.  */
  1950.     static void
  1951. foldUpdateIEMS(wp, top, bot)
  1952.     win_T    *wp;
  1953.     linenr_T    top;
  1954.     linenr_T    bot;
  1955. {
  1956.     linenr_T    start;
  1957.     linenr_T    end;
  1958.     fline_T    fline;
  1959.     void    (*getlevel)__ARGS((fline_T *));
  1960.     int        level;
  1961.     fold_T    *fp;
  1962.  
  1963.     /* Avoid problems when being called recursively. */
  1964.     if (invalid_top != (linenr_T)0)
  1965.     return;
  1966.  
  1967.     if (wp->w_foldinvalid)
  1968.     {
  1969.     /* Need to update all folds. */
  1970.     top = 1;
  1971.     bot = wp->w_buffer->b_ml.ml_line_count;
  1972.     wp->w_foldinvalid = FALSE;
  1973.  
  1974.     /* Mark all folds a maybe-small. */
  1975.     setSmallMaybe(&wp->w_folds);
  1976.     }
  1977.  
  1978. #ifdef FEAT_DIFF
  1979.     /* add the context for "diff" folding */
  1980.     if (foldmethodIsDiff(wp))
  1981.     {
  1982.     if (top > diff_context)
  1983.         top -= diff_context;
  1984.     else
  1985.         top = 1;
  1986.     bot += diff_context;
  1987.     }
  1988. #endif
  1989.  
  1990.     /* When deleting lines at the end of the buffer "top" can be past the end
  1991.      * of the buffer. */
  1992.     if (top > wp->w_buffer->b_ml.ml_line_count)
  1993.     top = wp->w_buffer->b_ml.ml_line_count;
  1994.  
  1995.     fold_changed = FALSE;
  1996.     fline.wp = wp;
  1997.     fline.off = 0;
  1998.     fline.lvl = 0;
  1999.     fline.lvl_next = -1;
  2000.     fline.start = 0;
  2001.     fline.end = MAX_LEVEL + 1;
  2002.     fline.had_end = MAX_LEVEL + 1;
  2003.  
  2004.     invalid_top = top;
  2005.     invalid_bot = bot;
  2006.  
  2007.     if (foldmethodIsMarker(wp))
  2008.     {
  2009.     getlevel = foldlevelMarker;
  2010.  
  2011.     /* Init marker variables to speed up foldlevelMarker(). */
  2012.     parseMarker(wp);
  2013.  
  2014.     /* Need to get the level of the line above top, it is used if there is
  2015.      * no marker at the top. */
  2016.     if (top > 1)
  2017.     {
  2018.         /* Get the fold level at top - 1. */
  2019.         level = foldLevelWin(wp, top - 1);
  2020.  
  2021.         /* The fold may end just above the top, check for that. */
  2022.         fline.lnum = top - 1;
  2023.         fline.lvl = level;
  2024.         getlevel(&fline);
  2025.  
  2026.         /* If a fold started here, we already had the level, if it stops
  2027.          * here, we need to use lvl_next.  Could also start and end a fold
  2028.          * in the same line. */
  2029.         if (fline.lvl > level)
  2030.         fline.lvl = level - (fline.lvl - fline.lvl_next);
  2031.         else
  2032.         fline.lvl = fline.lvl_next;
  2033.     }
  2034.     fline.lnum = top;
  2035.     getlevel(&fline);
  2036.     }
  2037.     else
  2038.     {
  2039.     fline.lnum = top;
  2040.     if (foldmethodIsExpr(wp))
  2041.     {
  2042.         getlevel = foldlevelExpr;
  2043.         /* start one line back, because a "<1" may indicate the end of a
  2044.          * fold in the topline */
  2045.         if (top > 1)
  2046.         --fline.lnum;
  2047.     }
  2048.     else if (foldmethodIsSyntax(wp))
  2049.         getlevel = foldlevelSyntax;
  2050. #ifdef FEAT_DIFF
  2051.     else if (foldmethodIsDiff(wp))
  2052.         getlevel = foldlevelDiff;
  2053. #endif
  2054.     else
  2055.         getlevel = foldlevelIndent;
  2056.  
  2057.     /* Backup to a line for which the fold level is defined.  Since it's
  2058.      * always defined for line one, we will stop there. */
  2059.     fline.lvl = -1;
  2060.     for ( ; !got_int; --fline.lnum)
  2061.     {
  2062.         /* Reset lvl_next each time, because it will be set to a value for
  2063.          * the next line, but we search backwards here. */
  2064.         fline.lvl_next = -1;
  2065.         getlevel(&fline);
  2066.         if (fline.lvl >= 0)
  2067.         break;
  2068.     }
  2069.     }
  2070.  
  2071.     start = fline.lnum;
  2072.     end = bot;
  2073.     /* Do at least one line. */
  2074.     if (start > end && end < wp->w_buffer->b_ml.ml_line_count)
  2075.     end = start;
  2076.     while (!got_int)
  2077.     {
  2078.     /* Always stop at the end of the file ("end" can be past the end of
  2079.      * the file). */
  2080.     if (fline.lnum > wp->w_buffer->b_ml.ml_line_count)
  2081.         break;
  2082.     if (fline.lnum > end)
  2083.     {
  2084.         /* For "marker", "expr"  and "syntax"  methods: If a change caused
  2085.          * a fold to be removed, we need to continue at least until where
  2086.          * it ended. */
  2087.         if (getlevel != foldlevelMarker
  2088.             && getlevel != foldlevelSyntax
  2089.             && getlevel != foldlevelExpr)
  2090.         break;
  2091.         if ((start <= end
  2092.             && foldFind(&wp->w_folds, end, &fp)
  2093.             && fp->fd_top + fp->fd_len - 1 > end)
  2094.             || (fline.lvl == 0
  2095.             && foldFind(&wp->w_folds, fline.lnum, &fp)
  2096.             && fp->fd_top < fline.lnum))
  2097.         end = fp->fd_top + fp->fd_len - 1;
  2098.         else if (getlevel == foldlevelSyntax
  2099.             && foldLevelWin(wp, fline.lnum) != fline.lvl)
  2100.         /* For "syntax" method: Compare the foldlevel that the syntax
  2101.          * tells us to the foldlevel from the existing folds.  If they
  2102.          * don't match continue updating folds. */
  2103.         end = fline.lnum;
  2104.         else
  2105.         break;
  2106.     }
  2107.  
  2108.     /* A level 1 fold starts at a line with foldlevel > 0. */
  2109.     if (fline.lvl > 0)
  2110.     {
  2111.         invalid_top = fline.lnum;
  2112.         invalid_bot = end;
  2113.         end = foldUpdateIEMSRecurse(&wp->w_folds,
  2114.                    1, start, &fline, getlevel, end, FD_LEVEL);
  2115.         start = fline.lnum;
  2116.     }
  2117.     else
  2118.     {
  2119.         if (fline.lnum == wp->w_buffer->b_ml.ml_line_count)
  2120.         break;
  2121.         ++fline.lnum;
  2122.         fline.lvl = fline.lvl_next;
  2123.         getlevel(&fline);
  2124.     }
  2125.     }
  2126.  
  2127.     /* There can't be any folds from start until end now. */
  2128.     foldRemove(&wp->w_folds, start, end);
  2129.  
  2130.     /* If some fold changed, need to redraw and position cursor. */
  2131.     if (fold_changed && wp->w_p_fen)
  2132.     changed_window_setting();
  2133.  
  2134.     /* If we updated folds past "bot", need to redraw more lines.  Don't do
  2135.      * this in other situations, the changed lines will be redrawn anyway and
  2136.      * this method can cause the whole window to be updated. */
  2137.     if (end != bot)
  2138.     {
  2139.     if (wp->w_redraw_top == 0 || wp->w_redraw_top > top)
  2140.         wp->w_redraw_top = top;
  2141.     if (wp->w_redraw_bot < end)
  2142.         wp->w_redraw_bot = end;
  2143.     }
  2144.  
  2145.     invalid_top = (linenr_T)0;
  2146. }
  2147.  
  2148. /* foldUpdateIEMSRecurse() {{{2 */
  2149. /*
  2150.  * Update a fold that starts at "flp->lnum".  At this line there is always a
  2151.  * valid foldlevel, and its level >= "level".
  2152.  * "flp" is valid for "flp->lnum" when called and it's valid when returning.
  2153.  * "flp->lnum" is set to the lnum just below the fold, if it ends before
  2154.  * "bot", it's "bot" plus one if the fold continues and it's bigger when using
  2155.  * the marker method and a text change made following folds to change.
  2156.  * When returning, "flp->lnum_save" is the line number that was used to get
  2157.  * the level when the level at "flp->lnum" is invalid.
  2158.  * Remove any folds from "startlnum" up to here at this level.
  2159.  * Recursively update nested folds.
  2160.  * Below line "bot" there are no changes in the text.
  2161.  * "flp->lnum", "flp->lnum_save" and "bot" are relative to the start of the
  2162.  * outer fold.
  2163.  * "flp->off" is the offset to the real line number in the buffer.
  2164.  *
  2165.  * All this would be a lot simpler if all folds in the range would be deleted
  2166.  * and then created again.  But we would loose all information about the
  2167.  * folds, even when making changes that don't affect the folding (e.g. "vj~").
  2168.  *
  2169.  * Returns bot, which may have been increased for lines that also need to be
  2170.  * updated as a result of a detected change in the fold.
  2171.  */
  2172.     static linenr_T
  2173. foldUpdateIEMSRecurse(gap, level, startlnum, flp, getlevel, bot, topflags)
  2174.     garray_T    *gap;
  2175.     int        level;
  2176.     linenr_T    startlnum;
  2177.     fline_T    *flp;
  2178.     void    (*getlevel)__ARGS((fline_T *));
  2179.     linenr_T    bot;
  2180.     int        topflags;    /* flags used by containing fold */
  2181. {
  2182.     linenr_T    ll;
  2183.     fold_T    *fp = NULL;
  2184.     fold_T    *fp2;
  2185.     int        lvl = level;
  2186.     linenr_T    startlnum2 = startlnum;
  2187.     linenr_T    firstlnum = flp->lnum;    /* first lnum we got */
  2188.     int        i;
  2189.     int        finish = FALSE;
  2190.     linenr_T    linecount = flp->wp->w_buffer->b_ml.ml_line_count - flp->off;
  2191.     int        concat;
  2192.  
  2193.     /*
  2194.      * If using the marker method, the start line is not the start of a fold
  2195.      * at the level we're dealing with and the level is non-zero, we must use
  2196.      * the previous fold.  But ignore a fold that starts at or below
  2197.      * startlnum, it must be deleted.
  2198.      */
  2199.     if (getlevel == foldlevelMarker && flp->start <= flp->lvl - level
  2200.                                   && flp->lvl > 0)
  2201.     {
  2202.     foldFind(gap, startlnum - 1, &fp);
  2203.     if (fp >= ((fold_T *)gap->ga_data) + gap->ga_len
  2204.                            || fp->fd_top >= startlnum)
  2205.         fp = NULL;
  2206.     }
  2207.  
  2208.     /*
  2209.      * Loop over all lines in this fold, or until "bot" is hit.
  2210.      * Handle nested folds inside of this fold.
  2211.      * "flp->lnum" is the current line.  When finding the end of the fold, it
  2212.      * is just below the end of the fold.
  2213.      * "*flp" contains the level of the line "flp->lnum" or a following one if
  2214.      * there are lines with an invalid fold level.  "flp->lnum_save" is the
  2215.      * line number that was used to get the fold level (below "flp->lnum" when
  2216.      * it has an invalid fold level).  When called the fold level is always
  2217.      * valid, thus "flp->lnum_save" is equal to "flp->lnum".
  2218.      */
  2219.     flp->lnum_save = flp->lnum;
  2220.     while (!got_int)
  2221.     {
  2222.     /* Updating folds can be slow, check for CTRL-C. */
  2223.     line_breakcheck();
  2224.  
  2225.     /* Set "lvl" to the level of line "flp->lnum".  When flp->start is set
  2226.      * and after the first line of the fold, set the level to zero to
  2227.      * force the fold to end.  Do the same when had_end is set: Previous
  2228.      * line was marked as end of a fold. */
  2229.     lvl = flp->lvl;
  2230.     if (lvl > MAX_LEVEL)
  2231.         lvl = MAX_LEVEL;
  2232.     if (flp->lnum > firstlnum
  2233.         && (level > lvl - flp->start || level >= flp->had_end))
  2234.         lvl = 0;
  2235.  
  2236.     if (flp->lnum > bot && !finish && fp != NULL)
  2237.     {
  2238.         /* For "marker" and "syntax" methods:
  2239.          * - If a change caused a nested fold to be removed, we need to
  2240.          *   delete it and continue at least until where it ended.
  2241.          * - If a change caused a nested fold to be created, or this fold
  2242.          *   to continue below its original end, need to finish this fold.
  2243.          */
  2244.         if (getlevel != foldlevelMarker
  2245.             && getlevel != foldlevelExpr
  2246.             && getlevel != foldlevelSyntax)
  2247.         break;
  2248.         if (lvl == level
  2249.             && foldFind(&fp->fd_nested, flp->lnum - fp->fd_top, &fp2))
  2250.         bot = fp2->fd_top + fp2->fd_len - 1 + fp->fd_top;
  2251.         else if (fp->fd_top + fp->fd_len <= flp->lnum && lvl >= level)
  2252.         finish = TRUE;
  2253.         else
  2254.         break;
  2255.     }
  2256.  
  2257.     /* At the start of the first nested fold and at the end of the current
  2258.      * fold: check if existing folds at this level, before the current
  2259.      * one, need to be deleted or truncated. */
  2260.     if (fp == NULL
  2261.         && (lvl != level
  2262.             || flp->lnum_save >= bot
  2263.             || flp->start != 0
  2264.             || flp->had_end <= MAX_LEVEL
  2265.             || flp->lnum == linecount))
  2266.     {
  2267.         /*
  2268.          * Remove or update folds that have lines between startlnum and
  2269.          * firstlnum.
  2270.          */
  2271.         while (!got_int)
  2272.         {
  2273.         /* set concat to 1 if it's allowed to concatenated this fold
  2274.          * with a previous one that touches it. */
  2275.         if (flp->start != 0 || flp->had_end <= MAX_LEVEL)
  2276.             concat = 0;
  2277.         else
  2278.             concat = 1;
  2279.  
  2280.         /* Find an existing fold to re-use.  Preferably one that
  2281.          * includes startlnum, otherwise one that ends just before
  2282.          * startlnum or starts after it. */
  2283.         if (foldFind(gap, startlnum, &fp)
  2284.             || (fp < ((fold_T *)gap->ga_data) + gap->ga_len
  2285.                 && fp->fd_top <= firstlnum)
  2286.             || foldFind(gap, firstlnum - concat, &fp)
  2287.             || (fp < ((fold_T *)gap->ga_data) + gap->ga_len
  2288.                 && ((lvl < level && fp->fd_top < flp->lnum)
  2289.                 || (lvl >= level
  2290.                        && fp->fd_top <= flp->lnum_save))))
  2291.         {
  2292.             if (fp->fd_top + fp->fd_len + concat > firstlnum)
  2293.             {
  2294.             /* Use existing fold for the new fold.  If it starts
  2295.              * before where we started looking, extend it.  If it
  2296.              * starts at another line, update nested folds to keep
  2297.              * their position, compensating for the new fd_top. */
  2298.             if (fp->fd_top >= startlnum && fp->fd_top != firstlnum)
  2299.             {
  2300.                 if (fp->fd_top > firstlnum)
  2301.                 /* like lines are inserted */
  2302.                 foldMarkAdjustRecurse(&fp->fd_nested,
  2303.                     (linenr_T)0, (linenr_T)MAXLNUM,
  2304.                     (long)(fp->fd_top - firstlnum), 0L);
  2305.                 else
  2306.                 /* like lines are deleted */
  2307.                 foldMarkAdjustRecurse(&fp->fd_nested,
  2308.                     (linenr_T)0,
  2309.                     (long)(firstlnum - fp->fd_top - 1),
  2310.                     (linenr_T)MAXLNUM,
  2311.                     (long)(fp->fd_top - firstlnum));
  2312.                 fp->fd_len += fp->fd_top - firstlnum;
  2313.                 fp->fd_top = firstlnum;
  2314.                 fold_changed = TRUE;
  2315.             }
  2316.             else if (flp->start != 0 && lvl == level
  2317.                            && fp->fd_top != firstlnum)
  2318.             {
  2319.                 /* Existing fold that includes startlnum must stop
  2320.                  * if we find the start of a new fold at the same
  2321.                  * level.  Split it.  Delete contained folds at
  2322.                  * this point to split them too. */
  2323.                 foldRemove(&fp->fd_nested, flp->lnum - fp->fd_top,
  2324.                               flp->lnum - fp->fd_top);
  2325.                 i = (int)(fp - (fold_T *)gap->ga_data);
  2326.                 foldSplit(gap, i, flp->lnum, flp->lnum - 1);
  2327.                 fp = (fold_T *)gap->ga_data + i + 1;
  2328.                 /* If using the "marker" or "syntax" method, we
  2329.                  * need to continue until the end of the fold is
  2330.                  * found. */
  2331.                 if (getlevel == foldlevelMarker
  2332.                     || getlevel == foldlevelExpr
  2333.                     || getlevel == foldlevelSyntax)
  2334.                 finish = TRUE;
  2335.             }
  2336.             break;
  2337.             }
  2338.             if (fp->fd_top >= startlnum)
  2339.             {
  2340.             /* A fold that starts at or after startlnum and stops
  2341.              * before the new fold must be deleted.  Continue
  2342.              * looking for the next one. */
  2343.             deleteFoldEntry(gap,
  2344.                      (int)(fp - (fold_T *)gap->ga_data), TRUE);
  2345.             }
  2346.             else
  2347.             {
  2348.             /* A fold has some lines above startlnum, truncate it
  2349.              * to stop just above startlnum.  */
  2350.             fp->fd_len = startlnum - fp->fd_top;
  2351.             foldMarkAdjustRecurse(&fp->fd_nested,
  2352.                 (linenr_T)fp->fd_len, (linenr_T)MAXLNUM,
  2353.                                (linenr_T)MAXLNUM, 0L);
  2354.             fold_changed = TRUE;
  2355.             }
  2356.         }
  2357.         else
  2358.         {
  2359.             /* Insert new fold.  Careful: ga_data may be NULL and it
  2360.              * may change! */
  2361.             i = (int)(fp - (fold_T *)gap->ga_data);
  2362.             if (foldInsert(gap, i) != OK)
  2363.             return bot;
  2364.             fp = (fold_T *)gap->ga_data + i;
  2365.             /* The new fold continues until bot, unless we find the
  2366.              * end earlier. */
  2367.             fp->fd_top = firstlnum;
  2368.             fp->fd_len = bot - firstlnum + 1;
  2369.             /* When the containing fold is open, the new fold is open.
  2370.              * The new fold is closed if the fold above it is closed.
  2371.              * The first fold depends on the containing fold. */
  2372.             if (topflags == FD_OPEN)
  2373.             {
  2374.             flp->wp->w_fold_manual = TRUE;
  2375.             fp->fd_flags = FD_OPEN;
  2376.             }
  2377.             else if (i <= 0)
  2378.             {
  2379.             fp->fd_flags = topflags;
  2380.             if (topflags != FD_LEVEL)
  2381.                 flp->wp->w_fold_manual = TRUE;
  2382.             }
  2383.             else
  2384.             fp->fd_flags = (fp - 1)->fd_flags;
  2385.             fp->fd_small = MAYBE;
  2386.             /* If using the "marker", "expr" or "syntax" method, we
  2387.              * need to continue until the end of the fold is found. */
  2388.             if (getlevel == foldlevelMarker
  2389.                 || getlevel == foldlevelExpr
  2390.                 || getlevel == foldlevelSyntax)
  2391.             finish = TRUE;
  2392.             fold_changed = TRUE;
  2393.             break;
  2394.         }
  2395.         }
  2396.     }
  2397.  
  2398.     if (lvl < level || flp->lnum > linecount)
  2399.     {
  2400.         /*
  2401.          * Found a line with a lower foldlevel, this fold ends just above
  2402.          * "flp->lnum".
  2403.          */
  2404.         break;
  2405.     }
  2406.  
  2407.     /*
  2408.      * The fold includes the line "flp->lnum" and "flp->lnum_save".
  2409.      */
  2410.     if (lvl > level)
  2411.     {
  2412.         /*
  2413.          * There is a nested fold, handle it recursively.
  2414.          */
  2415.         /* At least do one line (can happen when finish is TRUE). */
  2416.         if (bot < flp->lnum)
  2417.         bot = flp->lnum;
  2418.  
  2419.         /* Line numbers in the nested fold are relative to the start of
  2420.          * this fold. */
  2421.         flp->lnum = flp->lnum_save - fp->fd_top;
  2422.         flp->off += fp->fd_top;
  2423.         i = (int)(fp - (fold_T *)gap->ga_data);
  2424.         bot = foldUpdateIEMSRecurse(&fp->fd_nested, level + 1,
  2425.                        startlnum2 - fp->fd_top, flp, getlevel,
  2426.                           bot - fp->fd_top, fp->fd_flags);
  2427.         fp = (fold_T *)gap->ga_data + i;
  2428.         flp->lnum += fp->fd_top;
  2429.         flp->lnum_save += fp->fd_top;
  2430.         flp->off -= fp->fd_top;
  2431.         bot += fp->fd_top;
  2432.         startlnum2 = flp->lnum;
  2433.  
  2434.         /* This fold may end at the same line, don't incr. flp->lnum. */
  2435.     }
  2436.     else
  2437.     {
  2438.         /*
  2439.          * Get the level of the next line, then continue the loop to check
  2440.          * if it ends there.
  2441.          * Skip over undefined lines, to find the foldlevel after it.
  2442.          * For the last line in the file the foldlevel is always valid.
  2443.          */
  2444.         flp->lnum = flp->lnum_save;
  2445.         ll = flp->lnum + 1;
  2446.         while (!got_int)
  2447.         {
  2448.         if (++flp->lnum > linecount)
  2449.             break;
  2450.         flp->lvl = flp->lvl_next;
  2451.         getlevel(flp);
  2452.         if (flp->lvl >= 0 || flp->had_end <= MAX_LEVEL)
  2453.             break;
  2454.         }
  2455.         if (flp->lnum > linecount)
  2456.         break;
  2457.  
  2458.         /* leave flp->lnum_save to lnum of the line that was used to get
  2459.          * the level, flp->lnum to the lnum of the next line. */
  2460.         flp->lnum_save = flp->lnum;
  2461.         flp->lnum = ll;
  2462.     }
  2463.     }
  2464.  
  2465.     if (fp == NULL)    /* only happens when got_int is set */
  2466.     return bot;
  2467.  
  2468.     /*
  2469.      * Get here when:
  2470.      * lvl < level: the folds ends just above "flp->lnum"
  2471.      * lvl >= level: fold continues below "bot"
  2472.      */
  2473.  
  2474.     /* Current fold at least extends until lnum. */
  2475.     if (fp->fd_len < flp->lnum - fp->fd_top)
  2476.     {
  2477.     fp->fd_len = flp->lnum - fp->fd_top;
  2478.     fold_changed = TRUE;
  2479.     }
  2480.  
  2481.     /* Delete contained folds from the end of the last one found until where
  2482.      * we stopped looking. */
  2483.     foldRemove(&fp->fd_nested, startlnum2 - fp->fd_top,
  2484.                           flp->lnum - 1 - fp->fd_top);
  2485.  
  2486.     if (lvl < level)
  2487.     {
  2488.     /* End of fold found, update the length when it got shorter. */
  2489.     if (fp->fd_len != flp->lnum - fp->fd_top)
  2490.     {
  2491.         if (fp->fd_top + fp->fd_len > bot + 1)
  2492.         {
  2493.         /* fold coninued below bot */
  2494.         if (getlevel == foldlevelMarker
  2495.             || getlevel == foldlevelExpr
  2496.             || getlevel == foldlevelSyntax)
  2497.         {
  2498.             /* marker method: truncate the fold and make sure the
  2499.              * previously included lines are processed again */
  2500.             bot = fp->fd_top + fp->fd_len - 1;
  2501.             fp->fd_len = flp->lnum - fp->fd_top;
  2502.         }
  2503.         else
  2504.         {
  2505.             /* indent or expr method: split fold to create a new one
  2506.              * below bot */
  2507.             i = (int)(fp - (fold_T *)gap->ga_data);
  2508.             foldSplit(gap, i, flp->lnum, bot);
  2509.             fp = (fold_T *)gap->ga_data + i;
  2510.         }
  2511.         }
  2512.         else
  2513.         fp->fd_len = flp->lnum - fp->fd_top;
  2514.         fold_changed = TRUE;
  2515.     }
  2516.     }
  2517.  
  2518.     /* delete following folds that end before the current line */
  2519.     for (;;)
  2520.     {
  2521.     fp2 = fp + 1;
  2522.     if (fp2 >= (fold_T *)gap->ga_data + gap->ga_len
  2523.                           || fp2->fd_top > flp->lnum)
  2524.         break;
  2525.     if (fp2->fd_top + fp2->fd_len > flp->lnum)
  2526.     {
  2527.         if (fp2->fd_top < flp->lnum)
  2528.         {
  2529.         /* Make fold that includes lnum start at lnum. */
  2530.         foldMarkAdjustRecurse(&fp2->fd_nested,
  2531.             (linenr_T)0, (long)(flp->lnum - fp2->fd_top - 1),
  2532.             (linenr_T)MAXLNUM, (long)(fp2->fd_top - flp->lnum));
  2533.         fp2->fd_len -= flp->lnum - fp2->fd_top;
  2534.         fp2->fd_top = flp->lnum;
  2535.         fold_changed = TRUE;
  2536.         }
  2537.  
  2538.         if (lvl >= level)
  2539.         {
  2540.         /* merge new fold with existing fold that follows */
  2541.         foldMerge(fp, gap, fp2);
  2542.         }
  2543.         break;
  2544.     }
  2545.     fold_changed = TRUE;
  2546.     deleteFoldEntry(gap, (int)(fp2 - (fold_T *)gap->ga_data), TRUE);
  2547.     }
  2548.  
  2549.     /* Need to redraw the lines we inspected, which might be further down than
  2550.      * was asked for. */
  2551.     if (bot < flp->lnum - 1)
  2552.     bot = flp->lnum - 1;
  2553.  
  2554.     return bot;
  2555. }
  2556.  
  2557. /* foldInsert() {{{2 */
  2558. /*
  2559.  * Insert a new fold in "gap" at position "i".
  2560.  * Returns OK for success, FAIL for failure.
  2561.  */
  2562.     static int
  2563. foldInsert(gap, i)
  2564.     garray_T    *gap;
  2565.     int        i;
  2566. {
  2567.     fold_T    *fp;
  2568.  
  2569.     if (ga_grow(gap, 1) != OK)
  2570.     return FAIL;
  2571.     fp = (fold_T *)gap->ga_data + i;
  2572.     if (i < gap->ga_len)
  2573.     mch_memmove(fp + 1, fp, sizeof(fold_T) * (gap->ga_len - i));
  2574.     ++gap->ga_len;
  2575.     --gap->ga_room;
  2576.     ga_init2(&fp->fd_nested, (int)sizeof(fold_T), 10);
  2577.     return OK;
  2578. }
  2579.  
  2580. /* foldSplit() {{{2 */
  2581. /*
  2582.  * Split the "i"th fold in "gap", which starts before "top" and ends below
  2583.  * "bot" in two pieces, one ending above "top" and the other starting below
  2584.  * "bot".
  2585.  * The caller must first have taken care of any nested folds from "top" to
  2586.  * "bot"!
  2587.  */
  2588.     static void
  2589. foldSplit(gap, i, top, bot)
  2590.     garray_T    *gap;
  2591.     int        i;
  2592.     linenr_T    top;
  2593.     linenr_T    bot;
  2594. {
  2595.     fold_T    *fp;
  2596.     fold_T    *fp2;
  2597.     garray_T    *gap1;
  2598.     garray_T    *gap2;
  2599.     int        idx;
  2600.     int        len;
  2601.  
  2602.     /* The fold continues below bot, need to split it. */
  2603.     if (foldInsert(gap, i + 1) == FAIL)
  2604.     return;
  2605.     fp = (fold_T *)gap->ga_data + i;
  2606.     fp[1].fd_top = bot + 1;
  2607.     fp[1].fd_len = fp->fd_len - (fp[1].fd_top - fp->fd_top);
  2608.     fp[1].fd_flags = fp->fd_flags;
  2609.  
  2610.     /* Move nested folds below bot to new fold.  There can't be
  2611.      * any between top and bot, they have been removed by the caller. */
  2612.     gap1 = &fp->fd_nested;
  2613.     gap2 = &fp[1].fd_nested;
  2614.     (void)(foldFind(gap1, bot + 1 - fp->fd_top, &fp2));
  2615.     len = (int)((fold_T *)gap1->ga_data + gap1->ga_len - fp2);
  2616.     if (len > 0 && ga_grow(gap2, len) == OK)
  2617.     {
  2618.     for (idx = 0; idx < len; ++idx)
  2619.     {
  2620.         ((fold_T *)gap2->ga_data)[idx] = fp2[idx];
  2621.         ((fold_T *)gap2->ga_data)[idx].fd_top
  2622.                          -= fp[1].fd_top - fp->fd_top;
  2623.     }
  2624.     gap2->ga_len = len;
  2625.     gap2->ga_room -= len;
  2626.     gap1->ga_len -= len;
  2627.     gap1->ga_room += len;
  2628.     }
  2629.     fp->fd_len = top - fp->fd_top;
  2630.     fold_changed = TRUE;
  2631. }
  2632.  
  2633. /* foldRemove() {{{2 */
  2634. /*
  2635.  * Remove folds within the range "top" to and including "bot".
  2636.  * Check for these situations:
  2637.  *      1  2  3
  2638.  *      1  2  3
  2639.  * top     2  3  4  5
  2640.  *       2  3  4  5
  2641.  * bot       2  3  4  5
  2642.  *          3     5  6
  2643.  *          3     5  6
  2644.  *
  2645.  * 1: not changed
  2646.  * 2: trunate to stop above "top"
  2647.  * 3: split in two parts, one stops above "top", other starts below "bot".
  2648.  * 4: deleted
  2649.  * 5: made to start below "bot".
  2650.  * 6: not changed
  2651.  */
  2652.     static void
  2653. foldRemove(gap, top, bot)
  2654.     garray_T    *gap;
  2655.     linenr_T    top;
  2656.     linenr_T    bot;
  2657. {
  2658.     fold_T    *fp = NULL;
  2659.  
  2660.     if (bot < top)
  2661.     return;        /* nothing to do */
  2662.  
  2663.     for (;;)
  2664.     {
  2665.     /* Find fold that includes top or a following one. */
  2666.     if (foldFind(gap, top, &fp) && fp->fd_top < top)
  2667.     {
  2668.         /* 2: or 3: need to delete nested folds */
  2669.         foldRemove(&fp->fd_nested, top - fp->fd_top, bot - fp->fd_top);
  2670.         if (fp->fd_top + fp->fd_len > bot + 1)
  2671.         {
  2672.         /* 3: need to split it. */
  2673.         foldSplit(gap, (int)(fp - (fold_T *)gap->ga_data), top, bot);
  2674.         }
  2675.         else
  2676.         {
  2677.         /* 2: truncate fold at "top". */
  2678.         fp->fd_len = top - fp->fd_top;
  2679.         }
  2680.         fold_changed = TRUE;
  2681.         continue;
  2682.     }
  2683.     if (fp >= (fold_T *)(gap->ga_data) + gap->ga_len
  2684.         || fp->fd_top > bot)
  2685.     {
  2686.         /* 6: Found a fold below bot, can stop looking. */
  2687.         break;
  2688.     }
  2689.     if (fp->fd_top >= top)
  2690.     {
  2691.         /* Found an entry below top. */
  2692.         fold_changed = TRUE;
  2693.         if (fp->fd_top + fp->fd_len > bot)
  2694.         {
  2695.         /* 5: Make fold that includes bot start below bot. */
  2696.         foldMarkAdjustRecurse(&fp->fd_nested,
  2697.             (linenr_T)0, (long)(bot - fp->fd_top),
  2698.             (linenr_T)MAXLNUM, (long)(fp->fd_top - bot - 1));
  2699.         fp->fd_len -= bot - fp->fd_top + 1;
  2700.         fp->fd_top = bot + 1;
  2701.         break;
  2702.         }
  2703.  
  2704.         /* 4: Delete completely contained fold. */
  2705.         deleteFoldEntry(gap, (int)(fp - (fold_T *)gap->ga_data), TRUE);
  2706.     }
  2707.     }
  2708. }
  2709.  
  2710. /* foldMerge() {{{2 */
  2711. /*
  2712.  * Merge two adjecent folds (and the nested ones in them).
  2713.  * This only works correctly when the folds are really adjecent!  Thus "fp1"
  2714.  * must end just above "fp2".
  2715.  * The resulting fold is "fp1", nested folds are moved from "fp2" to "fp1".
  2716.  * Fold entry "fp2" in "gap" is deleted.
  2717.  */
  2718.     static void
  2719. foldMerge(fp1, gap, fp2)
  2720.     fold_T    *fp1;
  2721.     garray_T    *gap;
  2722.     fold_T    *fp2;
  2723. {
  2724.     fold_T    *fp3;
  2725.     fold_T    *fp4;
  2726.     int        idx;
  2727.     garray_T    *gap1 = &fp1->fd_nested;
  2728.     garray_T    *gap2 = &fp2->fd_nested;
  2729.  
  2730.     /* If the last nested fold in fp1 touches the first nested fold in fp2,
  2731.      * merge them recursively. */
  2732.     if (foldFind(gap1, fp1->fd_len - 1L, &fp3) && foldFind(gap2, 0L, &fp4))
  2733.     foldMerge(fp3, gap2, fp4);
  2734.  
  2735.     /* Move nested folds in fp2 to the end of fp1. */
  2736.     if (gap2->ga_len > 0 && ga_grow(gap1, gap2->ga_len) == OK)
  2737.     {
  2738.     for (idx = 0; idx < gap2->ga_len; ++idx)
  2739.     {
  2740.         ((fold_T *)gap1->ga_data)[gap1->ga_len]
  2741.                     = ((fold_T *)gap2->ga_data)[idx];
  2742.         ((fold_T *)gap1->ga_data)[gap1->ga_len].fd_top += fp1->fd_len;
  2743.         ++gap1->ga_len;
  2744.         --gap1->ga_room;
  2745.     }
  2746.     gap2->ga_len = 0;
  2747.     /* fp2->fd_nested.ga_room isn't updated, we delete it below */
  2748.     }
  2749.  
  2750.     fp1->fd_len += fp2->fd_len;
  2751.     deleteFoldEntry(gap, (int)(fp2 - (fold_T *)gap->ga_data), TRUE);
  2752.     fold_changed = TRUE;
  2753. }
  2754.  
  2755. /* foldlevelIndent() {{{2 */
  2756. /*
  2757.  * Low level function to get the foldlevel for the "indent" method.
  2758.  * Doesn't use any caching.
  2759.  * Returns a level of -1 if the foldlevel depends on surrounding lines.
  2760.  */
  2761.     static void
  2762. foldlevelIndent(flp)
  2763.     fline_T    *flp;
  2764. {
  2765.     char_u    *s;
  2766.     buf_T    *buf;
  2767.     linenr_T    lnum = flp->lnum + flp->off;
  2768.  
  2769.     buf = flp->wp->w_buffer;
  2770.     s = skipwhite(ml_get_buf(buf, lnum, FALSE));
  2771.  
  2772.     /* empty line or lines starting with a character in 'foldignore': level
  2773.      * depends on surrounding lines */
  2774.     if (*s == NUL || vim_strchr(flp->wp->w_p_fdi, *s) != NULL)
  2775.     {
  2776.     /* first and last line can't be undefined, use level 0 */
  2777.     if (lnum == 1 || lnum == buf->b_ml.ml_line_count)
  2778.         flp->lvl = 0;
  2779.     else
  2780.         flp->lvl = -1;
  2781.     }
  2782.     else
  2783.     flp->lvl = get_indent_buf(buf, lnum) / buf->b_p_sw;
  2784.     if (flp->lvl > flp->wp->w_p_fdn)
  2785.     flp->lvl = flp->wp->w_p_fdn;
  2786. }
  2787.  
  2788. /* foldlevelDiff() {{{2 */
  2789. #ifdef FEAT_DIFF
  2790. /*
  2791.  * Low level function to get the foldlevel for the "diff" method.
  2792.  * Doesn't use any caching.
  2793.  */
  2794.     static void
  2795. foldlevelDiff(flp)
  2796.     fline_T    *flp;
  2797. {
  2798.     if (diff_infold(flp->wp, flp->lnum + flp->off))
  2799.     flp->lvl = 1;
  2800.     else
  2801.     flp->lvl = 0;
  2802. }
  2803. #endif
  2804.  
  2805. /* foldlevelExpr() {{{2 */
  2806. /*
  2807.  * Low level function to get the foldlevel for the "expr" method.
  2808.  * Doesn't use any caching.
  2809.  * Returns a level of -1 if the foldlevel depends on surrounding lines.
  2810.  */
  2811.     static void
  2812. foldlevelExpr(flp)
  2813.     fline_T    *flp;
  2814. {
  2815. #ifndef FEAT_EVAL
  2816.     flp->start = FALSE;
  2817.     flp->lvl = 0;
  2818. #else
  2819.     win_T    *win;
  2820.     int        n;
  2821.     int        c;
  2822.     linenr_T    lnum = flp->lnum + flp->off;
  2823.  
  2824.     win = curwin;
  2825.     curwin = flp->wp;
  2826.     curbuf = flp->wp->w_buffer;
  2827.     set_vim_var_nr(VV_LNUM, lnum);
  2828.  
  2829.     flp->start = 0;
  2830.     flp->had_end = flp->end;
  2831.     flp->end = MAX_LEVEL + 1;
  2832.     if (lnum <= 1)
  2833.     flp->lvl = 0;
  2834.  
  2835.     n = eval_foldexpr(flp->wp->w_p_fde, &c);
  2836.     switch (c)
  2837.     {
  2838.     /* "a1", "a2", .. : add to the fold level */
  2839.     case 'a': if (flp->lvl >= 0)
  2840.           {
  2841.               flp->lvl += n;
  2842.               flp->lvl_next = flp->lvl;
  2843.           }
  2844.           flp->start = n;
  2845.           break;
  2846.  
  2847.     /* "s1", "s2", .. : subtract from the fold level */
  2848.     case 's': if (flp->lvl >= 0)
  2849.           {
  2850.               if (n > flp->lvl)
  2851.               flp->lvl_next = 0;
  2852.               else
  2853.               flp->lvl_next = flp->lvl - n;
  2854.               flp->end = flp->lvl_next + 1;
  2855.           }
  2856.           break;
  2857.  
  2858.     /* ">1", ">2", .. : start a fold with a certain level */
  2859.     case '>': flp->lvl = n;
  2860.           flp->lvl_next = n;
  2861.           flp->start = 1;
  2862.           break;
  2863.  
  2864.     /* "<1", "<2", .. : end a fold with a certain level */
  2865.     case '<': flp->lvl_next = n - 1;
  2866.           flp->end = n;
  2867.           break;
  2868.  
  2869.     /* "=": No change in level */
  2870.     case '=': flp->lvl_next = flp->lvl;
  2871.           break;
  2872.  
  2873.     /* "-1", "0", "1", ..: set fold level */
  2874.     default:  if (n < 0)
  2875.               /* Use the current level for the next line, so that "a1"
  2876.                * will work there. */
  2877.               flp->lvl_next = flp->lvl;
  2878.           else
  2879.               flp->lvl_next = n;
  2880.           flp->lvl = n;
  2881.           break;
  2882.     }
  2883.  
  2884.     /* If the level is unknown for the first or the last line in the file, use
  2885.      * level 0. */
  2886.     if (flp->lvl < 0)
  2887.     {
  2888.     if (lnum <= 1)
  2889.     {
  2890.         flp->lvl = 0;
  2891.         flp->lvl_next = 0;
  2892.     }
  2893.     if (lnum == curbuf->b_ml.ml_line_count)
  2894.         flp->lvl_next = 0;
  2895.     }
  2896.  
  2897.     curwin = win;
  2898.     curbuf = curwin->w_buffer;
  2899. #endif
  2900. }
  2901.  
  2902. /* parseMarker() {{{2 */
  2903. /*
  2904.  * Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and
  2905.  * "foldendmarkerlen".
  2906.  * Relies on the option value to have been checked for correctness already.
  2907.  */
  2908.     static void
  2909. parseMarker(wp)
  2910.     win_T    *wp;
  2911. {
  2912.     foldendmarker = vim_strchr(wp->w_p_fmr, ',');
  2913.     foldstartmarkerlen = (int)(foldendmarker++ - wp->w_p_fmr);
  2914.     foldendmarkerlen = (int)STRLEN(foldendmarker);
  2915. }
  2916.  
  2917. /* foldlevelMarker() {{{2 */
  2918. /*
  2919.  * Low level function to get the foldlevel for the "marker" method.
  2920.  * "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been
  2921.  * set before calling this.
  2922.  * Requires that flp->lvl is set to the fold level of the previous line!
  2923.  * Careful: This means you can't call this function twice on the same line.
  2924.  * Doesn't use any caching.
  2925.  * Sets flp->start when a start marker was found.
  2926.  */
  2927.     static void
  2928. foldlevelMarker(flp)
  2929.     fline_T    *flp;
  2930. {
  2931.     char_u    *startmarker;
  2932.     int        cstart;
  2933.     int        cend;
  2934.     char_u    *s;
  2935.     int        n;
  2936.  
  2937.     /* cache a few values for speed */
  2938.     startmarker = flp->wp->w_p_fmr;
  2939.     cstart = *startmarker;
  2940.     ++startmarker;
  2941.     cend = *foldendmarker;
  2942.  
  2943.     /* Default: no start found, next level is same as current level */
  2944.     flp->start = 0;
  2945.     flp->lvl_next = flp->lvl;
  2946.  
  2947.     s = ml_get_buf(flp->wp->w_buffer, flp->lnum + flp->off, FALSE);
  2948.     while (*s)
  2949.     {
  2950.     if (*s == cstart
  2951.           && STRNCMP(s + 1, startmarker, foldstartmarkerlen - 1) == 0)
  2952.     {
  2953.         /* found startmarker: set flp->lvl */
  2954.         s += foldstartmarkerlen;
  2955.         if (isdigit(*s))
  2956.         {
  2957.         n = atoi((char *)s);
  2958.         if (n > 0)
  2959.         {
  2960.             flp->lvl = n;
  2961.             flp->lvl_next = n;
  2962.             ++flp->start;
  2963.         }
  2964.         }
  2965.         else
  2966.         {
  2967.         ++flp->lvl;
  2968.         ++flp->lvl_next;
  2969.         ++flp->start;
  2970.         }
  2971.     }
  2972.     else if (*s == cend
  2973.           && STRNCMP(s + 1, foldendmarker + 1, foldendmarkerlen - 1) == 0)
  2974.     {
  2975.         /* found endmarker: set flp->lvl_next */
  2976.         s += foldendmarkerlen;
  2977.         if (isdigit(*s))
  2978.         {
  2979.         n = atoi((char *)s);
  2980.         if (n > 0)
  2981.         {
  2982.             flp->lvl = n;
  2983.             flp->lvl_next = n - 1;
  2984.             /* never start a fold with an end marker */
  2985.             if (flp->lvl_next > flp->lvl)
  2986.             flp->lvl_next = flp->lvl;
  2987.         }
  2988.         }
  2989.         else
  2990.         --flp->lvl_next;
  2991.     }
  2992.     else
  2993.         ++s;
  2994.     }
  2995. }
  2996.  
  2997. /* foldlevelSyntax() {{{2 */
  2998. /*
  2999.  * Low level function to get the foldlevel for the "syntax" method.
  3000.  * Doesn't use any caching.
  3001.  */
  3002.     static void
  3003. foldlevelSyntax(flp)
  3004.     fline_T    *flp;
  3005. {
  3006. #ifndef FEAT_SYN_HL
  3007.     flp->start = FALSE;
  3008.     flp->lvl = 0;
  3009. #else
  3010.     linenr_T    lnum = flp->lnum + flp->off;
  3011.     int        n;
  3012.  
  3013.     /* Use the maximum fold level at the start of this line and the next. */
  3014.     flp->lvl = syn_get_foldlevel(flp->wp, lnum);
  3015.     flp->start = FALSE;
  3016.     if (lnum < flp->wp->w_buffer->b_ml.ml_line_count)
  3017.     {
  3018.     n = syn_get_foldlevel(flp->wp, lnum + 1);
  3019.     if (n > flp->lvl)
  3020.     {
  3021.         flp->start = n - flp->lvl;    /* fold(s) start here */
  3022.         flp->lvl = n;
  3023.     }
  3024.     }
  3025. #endif
  3026. }
  3027.  
  3028. /* functions for storing the fold state in a View {{{1 */
  3029. /* put_folds() {{{2 */
  3030. #if defined(FEAT_SESSION) || defined(PROTO)
  3031. static int put_folds_recurse __ARGS((FILE *fd, garray_T *gap, linenr_T off));
  3032. static int put_foldopen_recurse __ARGS((FILE *fd, garray_T *gap, linenr_T off));
  3033.  
  3034. /*
  3035.  * Write commands to "fd" to restore the manual folds in window "wp".
  3036.  * Return FAIL if writing fails.
  3037.  */
  3038.     int
  3039. put_folds(fd, wp)
  3040.     FILE    *fd;
  3041.     win_T    *wp;
  3042. {
  3043.     if (foldmethodIsManual(wp))
  3044.     {
  3045.     if (put_line(fd, "silent! normal zE") == FAIL
  3046.         || put_folds_recurse(fd, &wp->w_folds, (linenr_T)0) == FAIL)
  3047.         return FAIL;
  3048.     }
  3049.  
  3050.     /* If some folds are manually opened/closed, need to restore that. */
  3051.     if (wp->w_fold_manual)
  3052.     return put_foldopen_recurse(fd, &wp->w_folds, (linenr_T)0);
  3053.  
  3054.     return OK;
  3055. }
  3056.  
  3057. /* put_folds_recurse() {{{2 */
  3058. /*
  3059.  * Write commands to "fd" to recreate manually created folds.
  3060.  * Returns FAIL when writing failed.
  3061.  */
  3062.     static int
  3063. put_folds_recurse(fd, gap, off)
  3064.     FILE    *fd;
  3065.     garray_T    *gap;
  3066.     linenr_T    off;
  3067. {
  3068.     int        i;
  3069.     fold_T    *fp;
  3070.  
  3071.     fp = (fold_T *)gap->ga_data;
  3072.     for (i = 0; i < gap->ga_len; i++)
  3073.     {
  3074.     /* Do nested folds first, they will be created closed. */
  3075.     if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL)
  3076.         return FAIL;
  3077.     if (fprintf(fd, "%ld,%ldfold", fp->fd_top + off,
  3078.                     fp->fd_top + off + fp->fd_len - 1) < 0
  3079.         || put_eol(fd) == FAIL)
  3080.         return FAIL;
  3081.     ++fp;
  3082.     }
  3083.     return OK;
  3084. }
  3085.  
  3086. /* put_folds_recurse() {{{2 */
  3087. /*
  3088.  * Write commands to "fd" to open and close manually opened/closed folds.
  3089.  * Returns FAIL when writing failed.
  3090.  */
  3091.     static int
  3092. put_foldopen_recurse(fd, gap, off)
  3093.     FILE    *fd;
  3094.     garray_T    *gap;
  3095.     linenr_T    off;
  3096. {
  3097.     int        i;
  3098.     fold_T    *fp;
  3099.  
  3100.     fp = (fold_T *)gap->ga_data;
  3101.     for (i = 0; i < gap->ga_len; i++)
  3102.     {
  3103.     if (fp->fd_flags != FD_LEVEL)
  3104.     {
  3105.         if (fp->fd_nested.ga_len > 0)
  3106.         {
  3107.         /* open/close nested folds while this fold is open */
  3108.         if (fprintf(fd, "%ld", fp->fd_top + off) < 0
  3109.             || put_eol(fd) == FAIL
  3110.             || put_line(fd, "normal zo") == FAIL)
  3111.             return FAIL;
  3112.         if (put_foldopen_recurse(fd, &fp->fd_nested, off + fp->fd_top)
  3113.             == FAIL)
  3114.             return FAIL;
  3115.         }
  3116.         if (fprintf(fd, "%ld", fp->fd_top + off) < 0
  3117.             || put_eol(fd) == FAIL
  3118.             || fprintf(fd, "normal z%c",
  3119.                     fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0
  3120.             || put_eol(fd) == FAIL)
  3121.         return FAIL;
  3122.     }
  3123.     ++fp;
  3124.     }
  3125.  
  3126.     return OK;
  3127. }
  3128. #endif /* FEAT_SESSION */
  3129.  
  3130. /* }}}1 */
  3131. #endif /* defined(FEAT_FOLDING) || defined(PROTO) */
  3132.